如何使用LINQ选择具有最高价值的商品? [英] How do I select the item with the highest value using LINQ?
问题描述
想象一下,您有一个像这样的课程:
Imagine you got a class like this:
class Foo {
string key;
int value;
}
您如何从IEnumeralbe<Foo>
中选择具有最高值的Foo?
How would you select the Foo with the highest value from an IEnumeralbe<Foo>
?
一个基本问题是使迭代次数保持较低(即为1),但这会影响可读性.毕竟,我能找到的最好的方法是:
A basic problem is to keep the number of iterations low (i.e. at 1), but that affects readability. After all, the best I could find was something along the lines of this:
IEnumerable<Foo> list;
Foo max = list.Aggregate ((l, r) => l.value > r.value ? l : r);
您能想到一种更好的方法吗?
Can you think of a more better way?
list.OrderByDescending(l => l.value).First();
是我的首选,但不是O(n).
list.OrderByDescending(l => l.value).First();
was my preferred option, but it is not O(n).
推荐答案
您可以获取 MoreLinq 中的cs"rel =" noreferrer> MaxBy LINQ扩展方法项目.那就是:
You can grab the MaxBy LINQ extension method from Jon Skeet's MoreLinq project. Then it's just:
Foo max = list.MaxBy(f => f.value);
这篇关于如何使用LINQ选择具有最高价值的商品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!