自定义对象的一个​​属性的最小值的LINQ索引c#

GKo*_*ser 2 c# linq min

我有一个自定义对象,其中包含一个具有许多属性的对象.

这是我的自定义对象: -

    private class ClosingBookItem
    {
        public IOrder Order;
        public double EntryPrice;

        // Maximum Adverse Effect Price
        public double MAEP;

        // closing order has a target of mean price
        public bool MidTarget;

        public ClosingBookItem(IOrder order, double entryPrice, double maep, bool midTarget)
        {
            Order       = order;
            EntryPrice  = entryPrice;
            MAEP        = maep;
            MidTarget   = midTarget;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Object Order有一个名为LimitPrice的Double属性.

我创建了这个自定义对象的列表: -

List<ClosingBookItem> closingsBook      = new List<ClosingBookItem>();
Run Code Online (Sandbox Code Playgroud)

如何在列表中返回包含Order.LimitPrice最小值的Item的索引?

我环顾四周但找不到好的描述,尝试过一些东西,但没有运气.

Tim*_*ter 5

您可以使用

double minLimitPrice = closingsBook.Min(b => b.Order.LimitPrice);
int index = closingsBook.FindIndex(b => b.Order.LimitPrice == minLimitPrice);
Run Code Online (Sandbox Code Playgroud)

另一种纯LINQ方法:

index = closingsBook.Select((b, ix) => new { Book = b, Index = ix })
    .OrderBy(x => x.Book.Order.LimitPrice)
    .First()
    .Index;
Run Code Online (Sandbox Code Playgroud)

如果要查找所有索引,则完全没问题:

IEnumerable<int> allIndexes = closingsBook.Where(b => b.Order.LimitPrice == minLimitPrice);
Console.WriteLine(String.Join(",", allIndexes));  // f.e.
Run Code Online (Sandbox Code Playgroud)

选择所有索引的纯LINQ方法:

IEnumerable<int> allIndexes = closingsBook.Select((b, ix) => new { Book = b, Index = ix })
    .GroupBy(x => x.Book.Order.LimitPrice)  // build groups per LimitPrice
    .OrderBy(g => g.Key)                    // order by that ascending
    .First()                                // take the group with lowest LimitPrice
    .Select(x => x.Index);                  // select the indexes of that group
Run Code Online (Sandbox Code Playgroud)