我有一个类名Product
的List
,我想知道具有最大值的元素的索引?
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));
我已经尝试过了,但没有得到答案!并收到错误:
"无法投射为产品">
您可以先映射每个项目,以便每个产品与其索引相关联,然后按降序排序并获取第一项:
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;
这需要排序
var maxObject = productList.OrderByDescending(item => item.ProductSize).First();
var index = productList.IndexOf(maxObject);
还有其他更简单的方法可以做到这一点。例如:MoreLINQ 中有一个扩展方法可以执行此操作。
看到这个问题
方法Max
将为您提供最大产品尺寸,而不是产品实例。这就是您收到此错误的原因。
你可以用OrderByDescending
来做到这一点:
var item = productList.OrderByDescending(i => i.ProductSize).First();
int index = productList.IndexOf(item);
这是一个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());
productList.Max(a=>a.ProductSize( 将返回 max ProductSize 值,而不是 Product 对象。 该条件应处于 WHERE 条件。