如何获取列表中最大元素的索引 <T>
How to Get the index of the Element which is Maximum in the List <T>
我有一个 List
和 class 名称 Product
我想知道具有 [= 的元素的 index 19=]最大值?
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));
我试过了,但没有得到答案!并出现错误:
"Unable to Cast as Product"
方法Max
将为您提供最大的 ProductSize,而不是 Product 的实例。这就是您收到此错误的原因。
你可以用 OrderByDescending
:
var item = productList.OrderByDescending(i => i.ProductSize).First();
int index = productList.IndexOf(item);
这需要排序
var maxObject = productList.OrderByDescending(item => item.ProductSize).First();
var index = productList.IndexOf(maxObject);
还有其他更简单的方法可以做到这一点。例如:MoreLINQ 中有一个扩展方法可以做到这一点。
参见this问题
productList.Max(a=>a.ProductSize) 将 return 最大 ProductSize 值,而不是 Product 对象。该条件应在 WHERE 条件下。
您可以先映射每个项目,使每个产品与其索引相关联,然后按降序排序并获得第一个项目:
int Index = productList
.Select((x, index) => new { Index = index, Product = x })
.OrderByDescending(x => x.Product.ProductSize).First().Index;
您不需要再次致电 IndexOf
!
您正在寻找 ArgMax
,它未在 Linq 中实现,但可以通过 Aggregate
:
轻松模拟
int Index = productList
.Select((item, index) => new { item, index })
.Aggregate((s, v) => v.item.ProductSize > s.item.ProductSize ? v : s)
.index;
这是 Enumerable.Range
的解决方案:
int index = Enumerable.Range(0, productList.Count)
.FirstOrDefault(i => productList[i].ProductSize == productList.Max(x => x.ProductSize));
假设列表不为空:
productList.Indexof(productList.OrderByDescending(a => a.ProductSize).First());
我有一个 List
和 class 名称 Product
我想知道具有 [= 的元素的 index 19=]最大值?
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));
我试过了,但没有得到答案!并出现错误:
"Unable to Cast as Product"
方法Max
将为您提供最大的 ProductSize,而不是 Product 的实例。这就是您收到此错误的原因。
你可以用 OrderByDescending
:
var item = productList.OrderByDescending(i => i.ProductSize).First();
int index = productList.IndexOf(item);
这需要排序
var maxObject = productList.OrderByDescending(item => item.ProductSize).First();
var index = productList.IndexOf(maxObject);
还有其他更简单的方法可以做到这一点。例如:MoreLINQ 中有一个扩展方法可以做到这一点。
参见this问题
productList.Max(a=>a.ProductSize) 将 return 最大 ProductSize 值,而不是 Product 对象。该条件应在 WHERE 条件下。
您可以先映射每个项目,使每个产品与其索引相关联,然后按降序排序并获得第一个项目:
int Index = productList
.Select((x, index) => new { Index = index, Product = x })
.OrderByDescending(x => x.Product.ProductSize).First().Index;
您不需要再次致电 IndexOf
!
您正在寻找 ArgMax
,它未在 Linq 中实现,但可以通过 Aggregate
:
int Index = productList
.Select((item, index) => new { item, index })
.Aggregate((s, v) => v.item.ProductSize > s.item.ProductSize ? v : s)
.index;
这是 Enumerable.Range
的解决方案:
int index = Enumerable.Range(0, productList.Count)
.FirstOrDefault(i => productList[i].ProductSize == productList.Max(x => x.ProductSize));
假设列表不为空:
productList.Indexof(productList.OrderByDescending(a => a.ProductSize).First());