Reputation: 2051
I'm writing a LINQ query where I have to select the last result in a list.
Which is more efficient?
.OrderByDescending(x => x.Id).First();
or
.Last();
Upvotes: 0
Views: 44
Reputation: 30464
Neither can be said to be more efficient. They do different things.
.Last();
This one returns the last element of a sequence (if there is one), without ordering
.OrderByDescending(x => x.Id).First();
This one returns you the element that would be last if you'd order in ascending order, if there is one. It will give be the same result as:
.OrderBy(x => x.Id).Last();
var sequence = {4, 1, 3}
var a = sequence.Last(); // result: 3
var b = sequence.OrderByDescending(x => x.Id) // intermediate result: 4, 3, 1
.First(); // final result: 4
var c = sequence.OrderBy(x => x.Id) // intermediate result: 1, 3, 4
.Last(); // final result: 4
b is more efficient than c, because after ordering the enumerator only has to MoveNext to the first element, while for c the enumerator has to MoveNext(), until there are no more elements.
Upvotes: 1