theringostarrs - 1 year ago 75

C# Question

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`

I can manage to get the highest value of the

`Height`

Can I do this with Linq? How?

Answer Source

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