I have the following LINQ query:
Person .OrderBy(x => x.FirstName) .Where(x => x.FirstName.Contains("a"));
I can also write this query in the following way:
Person .Where(x => x.FirstName.Contains("a")) .OrderBy(x => x.FirstName);
Both of them have the same result. So here’s my question,
What is the difference between the two queries? Which one is better? And why?
If you use Linq-To-Entities(or whatever database provider), there might be no difference at all, because the database will take care of the optimization. But in general and especially with Linq-To-Objects the latter is better, because it is more efficient to order less.
Also Guru is right with his comment that the result could be different in theory.
Enumerable.Where does not guarantee the order in the documentation. But they won’t change it because they would break a lot of code(it’s mentioned here that the order ist stable if the input sequence was ordered).
Edit: Actually some providers already change that order arbitrarily(for example PLINQ).
I have asked a similar question long time ago which answer you might find helpful:
Order of LINQ extension methods does not affect performance? Note that it’s just about Linq-To-Objects.
Answered By – Tim Schmelter
Answer Checked By – Pedro (BugsFixing Volunteer)