mafu
mafu

Reputation: 32640

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;
}

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 (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?

Edit: list.OrderByDescending(l => l.value).First(); was my preferred option, but it is not O(n).

Upvotes: 1

Views: 2147

Answers (3)

tzaman
tzaman

Reputation: 47770

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);

Upvotes: 7

EgorBo
EgorBo

Reputation: 6142

Foo foo = list.Max();

But you have to implement IComparable interface for Foo type;

Upvotes: 1

Adam Ruth
Adam Ruth

Reputation: 3655

Here's another option:

list.OrderByDescending(l => l.value).First();

or

list.OrderBy(l => l.value).Last();

Upvotes: 2

Related Questions