Is there any difference in (asymptotic) performance between
var a = Orders.OrderBy(order => order.Date).First()
and
var y = Orders.Where(order => order.Date == Orders.Min(x => x.Date)).ToList();
i.e. will First() perform the OrderBy()? I'm guessing no. MSDN says enumerating the collection via foreach och GetEnumerator does but the phrasing does not exclude other extensions.
LINQ OrderBy operator comes first in LINQ Sorting Operators. OrderBy operator sort the sequence (collection) based on particular property in ascending order. We can use OrderBy operator both in Query Syntax and Method Syntax.
OrderBy" function utilizes the default comparer for a string. That comparer is not necessarily going to return a sort order based on the ASCII code. For a list of all the different string comparers, see the article on MSDN.
OrderByDescending Operator If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.
A few things:
OrderBy()
orders from small to large, so your two alternatives return different elementsWhere()
is typically lazy, so your second expression doesn't actually do any computation at all - not until used.First()
on it recognizes (either at compile or run-time) that it's running on an ordered enumerable and instead of sorting, opts to return the (first) minimum element.IEnumerable<T>
provider, OrderBy
happens to return an enumerable that fully buffers and sorts the input each time the first element is retrieved - so, in the common basic Linq-to-objects case, OrderBy().First()
is comparable to OrderBy().ToArray()
.Remeber that linq is just a bunch of function names - each provider may choose to implement these differently, so the above only holds for the System.Linq IEnumerable query provider, and not necessarily others.
First
will return the first entry of the IEnumerable passed to it. Since the IEnumerable passed to First
is the result of OrderBy
your question can be rephrased to "Does OrderBy
work", and, yes it does.
First
cannot defer the execution of OrderBy
because it returns the result right away. For example:
var numbers = new int[] { 9, 3, 4, 6, 7 };
var num = numbers.First();
Console.WriteLine(num);
num = numbers.OrderBy(i => i).First();
Console.WriteLine(num);
Console.ReadLine();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With