How to perform .Max() on a property of all objects in a collection and return the object with maximum value

theringostarrs picture theringostarrs · Jul 9, 2009 · Viewed 382k times · Source

I have a list of objects that have two int properties. The list is the output of another linq query. The object:

public class DimensionPair  
{
    public int Height { get; set; }
    public int Width { get; set; }
}

I want to find and return the object in the list which has the largest Height property value.

I can manage to get the highest value of the Height value but not the object itself.

Can I do this with Linq? How?

Answer

Jon Skeet picture Jon Skeet · Jul 9, 2009

We have an extension method to do exactly this in MoreLINQ. You can look at the implementation there, but basically it's a case of iterating through the data, remembering the maximum element we've seen so far and the maximum value it produced under the projection.

In your case you'd do something like:

var item = items.MaxBy(x => x.Height);

This is better (IMO) than any of the solutions presented here other than Mehrdad's second solution (which is basically the same as MaxBy):

  • It's O(n) unlike the previous accepted answer which finds the maximum value on every iteration (making it O(n^2))
  • The ordering solution is O(n log n)
  • Taking the Max value and then finding the first element with that value is O(n), but iterates over the sequence twice. Where possible, you should use LINQ in a single-pass fashion.
  • It's a lot simpler to read and understand than the aggregate version, and only evaluates the projection once per element