Imagine you got a class like this:
class Foo {
string key;
int value;
}
How would you select the Foo with the highest value from an IEnumeralbe<Foo>
?
A basic problem is to keep the number of iterations low (ie 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?
Edit: list.OrderByDescending(l => l.value).First();
was my preferred option, but it is not O(n).
Here's another option:
list.OrderByDescending(l => l.value).First();
or
list.OrderBy(l => l.value).Last();
Foo foo = list.Max();
但是您必须为Foo类型实现IComparable接口;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.