I understand that executing operations in different orders will yield different performance such as the difference between the following slow query:
List
The answer is going to be different for different LINQ providers. In particular, the story is very different for LINQ to Objects and say LINQ to Entities.
In LINQ to Objects, the Where operator accepts the filter as Func
static void Main() {
List results = items.Where(MyFilter).ToList();
static boolean MyFilter(TestItem item) {
return item.Item1 == 12 &&
item.Item2 != null &&
item.Item2.SubItem == 65 &&
item.Item3.Equals(anotherThingy)
}
The main thing to notice is that MyFilter is an ordinary C# method and so ordinary C# rules apply, including the short-circuiting behavior of &&. Consequently, the conditions will be evaluated in the order you wrote them. LINQ to Objects can invoke MyFilter on different input elements, but it cannot change what MyFilter does.
In LINQ to Entities and LINQ to SQL, the Where operator accepts the filter as Expression
In LINQ to Entities and LINQ to SQL cases, the expression tree will be translated to SQL. And then it is up to the database server to decide how to execute the query. The server is definitely allowed to reorder the conditions, and it may do even more substantial optimizations. For example, if the SQL table contains an index on one of the columns referenced in the condition, the server can choose to use the index and avoid even looking at rows that don't match that particular condition part.