如何使用LINQ找到最小 [英] How to use linq to find the minimum
问题描述
我有一个 A级{公众持股量分数; ...}
和的IEnumerable< A>项目
,想找到 A
其具有最小比分。
I have a class A { public float Score; ... }
and an IEnumerable<A> items
and would like to find the A
which has minimal score.
使用 items.Min(X => x.Score)。
给出了最低得分,而不是实例与最低得分
Using items.Min(x => x.Score)
gives the minimal score and not the instance with minimal score.
我怎么能只通过我的数据迭代的一次获取实例
How can I get the instance by iterating only once through my data?
修改:只要有三个主要的解决方案:
Edit: So long there are three main solutions:
-
编写一个扩展方法(由Svish提议)。 赞成的:易于使用和评估每个项目的得分也只有一次。的缺点的:需要一个扩展方法。 (我这个选用的解决方案我的应用程序。)
Writing an extension method (proposed by Svish). Pros: Easy to use and evaluates Score only once per item. Cons: Needs an extension method. (I choosed this solution for my application.)
使用聚合(由丹尼尔·伦肖提议)。 赞成的:使用内置的LINQ的方法。的缺点的:略模糊处理,以未经训练的眼睛,并呼吁评估不止一次
Using Aggregate (proposed by Daniel Renshaw). Pros: Uses a built-in LINQ method. Cons: Slightly obfuscated to the untrained eye and calls evaluator more than once.
实现IComparable的(由cyberzed提议)。 赞成的:可以直接使用Linq.Min。的缺点的:修正了一个比较器 - 执行的最小计算时不能自由选择比较器
Implementing IComparable (proposed by cyberzed). Pros: Can use Linq.Min directly. Cons: Fixed to one comparer - can not freely choose comparer when performing the minimum computation.
推荐答案
有一个看 MinBy 扩展方法在 morelinq 通过乔恩斯基特(除非我错了)。
Have a look at the MinBy extension method in morelinq by Jon Skeet (unless I'm mistaken).
这篇关于如何使用LINQ找到最小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!