我有一系列元素。我想从这些元素中找到最低的值,但它们没有属性,我必须先计算该值并进行比较。我的伪代码: int currentLowestValue = int.MaxValue; MyObj targetElement = null; for (int i = 0; i < elements.Length; i++) { MyObj ele = elements[i]; int val = ele.CalculateValue() + GetOtherValue(); if (val < currentLowestValue) { targetElement = ele; currentLowestValue = val; } }如何选择ele.CalculateValue() + GetOtherValue();使用Linq计算出的最小值的元素?
2 回答

墨色风雨
TA贡献1853条经验 获得超6个赞
基于如何使用LINQ选择具有最小或最大属性值的对象
MyObj targetElement = elements.Aggregate((curMin, x) => (curMin == null || x.CalculateValue() < curMin.CalculateValue() ? x : curMin));
int currentLowestValue = targetElement.CalculateValue() + GetOtherValue();
由于值GetOtherValue() 似乎是静态的(不变),因此在计算中不需要它来查找具有最小值的元素。如果此方法不是幂等的,则需要将其添加到循环中,并将结果缓存在聚合中。
没有找到匹配的内容?试试慕课网站内搜索吧
- 2 回答
- 0 关注
- 224 浏览
添加回答
举报
0/150
提交
取消