This is purely for my own knowledge, if I were going to write the code I would just use .Max().
At first thought .Max() only has to do a single pass through numbers to find the max, while the second way has to sort the entire thing enumerable then find the first one. So it’s O(n) vs O(n lg n). But then I was thinking maybe it knows it only needs the highest and just grabs it.
Question:
Is LINQ and/or the compiler smart enough to figure out that it doesn’t need to sort the entire enumerable and boils the code down to essentially the same as .Max()? Is there a quantifiable way to find out?
IEnumerable<int> numbers = Enumerable.Range(1, 1000);
int max = numbers.Max();
int max2 = numbers.OrderByDescending(x => x).First();
If you are talking about straight LINQ to Objects, then no, it doesn’t optimize for that.
Presumably another LINQ provider could do, but that’s up to the particulars of the implementation.
For Enumerable, the implementations that Reflector gives me are:
and for
First()