Does the order of LINQ functions matter?

It will depend on the LINQ provider in use. For LINQ to Objects, that could certainly make a huge difference. Assume we’ve actually got:

var query = myCollection.OrderBy(item => item.CreatedDate)
                        .Where(item => item.Code > 3);

var result = query.Last();

That requires the whole collection to be sorted and then filtered. If we had a million items, only one of which had a code greater than 3, we’d be wasting a lot of time ordering results which would be thrown away.

Compare that with the reversed operation, filtering first:

var query = myCollection.Where(item => item.Code > 3)
                        .OrderBy(item => item.CreatedDate);

var result = query.Last();

This time we’re only ordering the filtered results, which in the sample case of “just a single item matching the filter” will be a lot more efficient – both in time and space.

It also could make a difference in whether the query executes correctly or not. Consider:

var query = myCollection.Where(item => item.Code != 0)
                        .OrderBy(item => 10 / item.Code);

var result = query.Last();

That’s fine – we know we’ll never be dividing by 0. But if we perform the ordering before the filtering, the query will throw an exception.

Leave a Comment