Which query has better performance to return an object which has the max value for a specific property?
var i = from item in listOfItems
orderby item.Number descending
select item;
or:
var i = from item in listOfItems
where item.Number== (from l in listOfItems select item).Max(l => l.Number)
select item;
In SQL, the two queries are translated into (at least, if you do a .FirstOrDefault() in the resulting IEnumerables to select the wanted object):
I can’t say which would be faster based on anything factual, but I’d go with the first order-by solution.
-* Edited to address querying the database *-
If you are querying an in memory collection, the difference should be very small.
However, here is the results of an entirely unscientific test by querying 100.000 semirandom numbers in the two different ways of querying each, 10 times:
Here is the entire LINQPad script: