【问题标题】:How to Get the index of the Element which is Maximum in the List <T>如何获取列表<T>中最大元素的索引
【发布时间】:2018-05-11 06:37:40
【问题描述】:

我有一个List,类名Product,我想知道最大值元素的索引

class Product
{
    public int ProductNumber { get; set; }
    public int ProductSize { get; set; }
}

List<Product> productList = new List<Product>();

int Index = productList.Indexof(productList.Max(a => a.ProductSize)); 

我试过这个,但没有得到答案!并得到一个错误:

“无法投射为产品”

【问题讨论】:

  • 如果性能很重要,请执行var indexOfMax = productList.Select((item, index) =&gt; new { item, index }).Aggregate((a, b) =&gt; a.item.ProductSize &gt; b.item.ProductSize ? a : b).index;

标签: c# list max indexof


【解决方案1】:

您可以先映射每个项目,使每个产品与其索引相关联,然后按降序排列并获取第一个项目:

int Index = productList
    .Select((x, index) => new { Index = index, Product = x })
    .OrderByDescending(x => x.Product.ProductSize).First().Index;

您无需再次致电IndexOf

【讨论】:

    【解决方案2】:

    您正在寻找未在 Linq 中实现但可以通过 Aggregate 轻松模拟的 ArgMax

      int Index = productList
        .Select((item, index) => new { item, index })
        .Aggregate((s, v) => v.item.ProductSize > s.item.ProductSize ? v : s)
        .index;
    

    【讨论】:

      【解决方案3】:

      这需要排序

      var maxObject = productList.OrderByDescending(item => item.ProductSize).First();
      var index = productList.IndexOf(maxObject);
      

      还有其他更简单的方法可以做到这一点。例如:MoreLINQ 中有一个扩展方法可以做到这一点。

      this问题

      【讨论】:

        【解决方案4】:

        Max 方法将为您提供最大的 ProductSize,而不是 Product 的实例。这就是您收到此错误的原因。

        您可以使用OrderByDescending

        var item = productList.OrderByDescending(i => i.ProductSize).First();
        int index = productList.IndexOf(item);
        

        【讨论】:

        • 您的意思是:productList.OrderByDescending(i =&gt; i.ProductSize).First()
        【解决方案5】:

        这是Enumerable.Range的解决方案:

        int index = Enumerable.Range(0, productList.Count)
                              .FirstOrDefault(i => productList[i].ProductSize == productList.Max(x => x.ProductSize));
        

        DEMO HERE

        【讨论】:

          【解决方案6】:

          假设列表不为空:

          productList.Indexof(productList.OrderByDescending(a => a.ProductSize).First());
          

          【讨论】:

            【解决方案7】:

            productList.Max(a=>a.ProductSize) 将返回最大 ProductSize 值,而不是 Product 对象。该条件应处于 WHERE 条件。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2022-08-16
              • 1970-01-01
              • 2013-12-03
              • 1970-01-01
              • 2012-11-15
              • 1970-01-01
              • 2018-07-09
              • 1970-01-01
              相关资源
              最近更新 更多