我有List
,类名为Product
,我想知道最大值的元素的索引?< / p>
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));
我试过这个但是没有得到答案!并收到错误:
“无法投放为产品”
答案 0 :(得分:2)
您可以先映射每个项目,使每个产品与其索引相关联,然后按降序排序并获取第一个项目:
int Index = productList
.Select((x, index) => new { Index = index, Product = x })
.OrderByDescending(x => x.Product.ProductSize).First().Index;
您无需再次致电IndexOf
!
答案 1 :(得分:1)
您正在寻找 Linq 中未实现的ArgMax
,但可以通过Aggregate
轻松模拟:
int Index = productList
.Select((item, index) => new { item, index })
.Aggregate((s, v) => v.item.ProductSize > s.item.ProductSize ? v : s)
.index;
答案 2 :(得分:0)
方法Max
将为您提供最大的ProductSize,而不是Product的实例。这就是您收到此错误的原因。
您可以使用OrderByDescending
执行此操作:
var item = productList.OrderByDescending(i => i.ProductSize).First();
int index = productList.IndexOf(item);
答案 3 :(得分:0)
这需要排序
var maxObject = productList.OrderByDescending(item => item.ProductSize).First();
var index = productList.IndexOf(maxObject);
还有其他更简单的方法可以做到这一点。例如:MoreLINQ中有一种扩展方法可以执行此操作。
请参阅this问题
答案 4 :(得分:0)
以下是Enumerable.Range
的解决方案:
int index = Enumerable.Range(0, productList.Count)
.FirstOrDefault(i => productList[i].ProductSize == productList.Max(x => x.ProductSize));
<强> DEMO HERE 强>
答案 5 :(得分:0)
假设列表不为空:
productList.Indexof(productList.OrderByDescending(a => a.ProductSize).First());
答案 6 :(得分:-1)
productList.Max(a =&gt; a.ProductSize)将返回max ProductSize值,而不是Product对象。该条件应该在WHERE条件下。