我有一个自定义对象,其中包含一个具有许多属性的对象。
这是我的自定义对象:-
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;
}
}
对象订单有一个名为 LimitPrice 的 Double 属性。
我已经创建了这个自定义对象的列表:-
List<ClosingBookItem> closingsBook = new List<ClosingBookItem>();
如何返回列表中包含 Order.LimitPrice 最小值的项目索引?
我环顾四周,但找不到好的描述,并尝试了一些方法,但没有成功。
最佳答案
您可以使用
double minLimitPrice = closingsBook.Min(b => b.Order.LimitPrice);
int index = closingsBook.FindIndex(b => b.Order.LimitPrice == minLimitPrice);
另一种纯 LINQ 方法:
index = closingsBook.Select((b, ix) => new { Book = b, Index = ix })
.OrderBy(x => x.Book.Order.LimitPrice)
.First()
.Index;
如果你想查找所有索引,完全没问题:
IEnumerable<int> allIndexes = closingsBook.Where(b => b.Order.LimitPrice == minLimitPrice);
Console.WriteLine(String.Join(",", allIndexes)); // f.e.
选择所有索引的纯 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
关于c# - 自定义对象 c# 的一个属性的最小值的 LINQ 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31110652/