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

标签 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;
        }
    }

对象订单有一个名为 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/

相关文章:

c# - 查找由 Selenium WebDriver 启动的浏览器进程的 PID

javascript - 获取随机数并关注限制(抛物线)

c - 如何将 rand() 结果设置为一定范围内的值,包括负值?

c# - 为什么编译器不能推断此选择调用的类型?

c# - Linq 按子集合排序

java - 如何使用 math.max 和 math.min 省略高分和低分

C# 并发和代理

c# - 使用带有打印对话框的 Word Interop 进行打印

c# - Python 到 C# 代码解释

c# - 如何从其父级返回集合的第一个对象