Will First() perform the OrderBy()?

linq, linq-extensions

Solution

A few things:

- `OrderBy()` orders from small to large, so your two alternatives return different elements

- `Where()` is typically lazy, so your second expression doesn't actually do any computation at all - not until used.

- In principle, the behavior in question depends on the query provider. For example, you might indeed expect the sql-server linq query provider to deal with this differently than the IEnumerable query provider. A query provider might choose to have the return value of "OrderBy" be sufficiently specialized such that calling `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.

- Specifically for the `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.

Problem

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.

Original source