difference of calling OrderBy() before Where() and vice versa

ado.net, c#, linq

Solution

If your query is actually going against a database via Entity Framework, Linq-to-SQL, or another such provider, then the order of invocation in your example does not matter.

If this is happening against an in-memory collection, you are ordering before filtering, which would be less ideal than applying the filter first. You are ordering elements that you might just discard, for example. (Ordering involves comparatively a lot of work. Filtering first reduces that work.)

That said, I would argue for the second form even if going against the database, as the same code would be equally valid for in-memory querying, so develop the habit of writing code in the normally ideal manner. It's also arguable that you would expect to see filtering prior to ordering as a matter of thought process.

Problem

I am wondering... In my application, I am doing something like this: ``` var threads = scykDb.Threads .AsQueryable() .Where(condition) .OrderByDescending(t => t.DateCreated) .Skip(threadsToSkip) .Take(threadsPerPage) .Select(t => t) .ToList(); ``` What would happen, if i did OrderBy() before Where()? Does it matter and what about skip() or take(), does position of those matters too? ``` var threads = scykDb.Threads .AsQueryable() .OrderByDescending(t => t.DateCreated) .Where(condition) .Skip(threadsToSkip) .Take(threadsPerPage) .Select(t => t) .ToList(); ```

Original source

Related problems