首页 > 解决方案 > 如何获取列表中最大元素的索引

问题描述

我有一个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)); 

我已经尝试过了,但没有得到答案!并得到一个错误:

“无法投射为产品”

标签: c#listmaxindexof

解决方案


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

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

你不需要另一个电话IndexOf


推荐阅读