views:

68

answers:

3

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

+2  A: 

Here's another option:

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

or

list.OrderBy(l => l.value).Last();
Adam Ruth
This is what I was using earlier, but I think it is not O(n).
mafutrct
True, it wouldn't be.
Adam Ruth
+1  A: 
Foo foo = list.Max();

But you have to implement IComparable interface for Foo type;

Nagg
Nice idea, but I can't change Foo.
mafutrct
+5  A: 

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);
tzaman
Now that's appealing.
mafutrct
Yeah, morelinq is awesome.
tzaman