c# - 如何获取列表中最大元素的索引
问题描述
我有一个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));
我已经尝试过了,但没有得到答案!并得到一个错误:
“无法投射为产品”
解决方案
您可以首先映射每个项目,以便每个产品与其索引相关联,然后按降序排列并获取第一个项目:
int Index = productList
.Select((x, index) => new { Index = index, Product = x })
.OrderByDescending(x => x.Product.ProductSize).First().Index;
你不需要另一个电话IndexOf
!
推荐阅读
- arduino - 将浮点数据类型从 Arduino 发送到 ESP32 (NodeMCU)
- android - 不能用谷歌账号登录
- ruby-on-rails - 为什么此代码返回“Authors#new 中的 NoMethodError”错误?
- highcharts - 来自传感器数据的 HighStock 图表
- excel - 将 MsgBox 文本复制到剪贴板
- xamarin - OnResume() 和 OnSleep() 已调用但无法正常工作
- python - 在 Python 中加密和解密文件
- python-3.x - 完整值未使用 Python 写入文件
- sql - 设置数据库复制时启动快照代理时出现异常
- php - 是否可以为 Vue 组件使用刀片模板?