views:

44

answers:

2

Are the following two queries equivalent? If they are not equivalent, which performs better? Is there a way I can see the sql output of the queries?

var query1 = items.Where(i => i.Enabled == true).Where(i => i.Name == "Bob");

var query2 = items.Where(i => i.Enabled == true && i.Name == "Bob");
+2  A: 

Both queries will translate to the same SQL - you can use a tool like LinqPad to verify this if you want (I just did). The LINQ provider that translate your expression trees into T-SQL is smart enough to understand that these queries are synonymous. Of course this means that both queries will perform equally as well.

Andrew Hare
+2  A: 

As Andrew says, the two options are equivalent. One practically useful difference is that you can easily generate conditions in the Where clause programmatically. For example if you wanted to exclude certain names:

var query = items;
for(string name in excluded) 
  query = query.Where(i => i.Name != excluded); 

This is something that cannot be done easily when writing query using && operator.

Tomas Petricek
whats wrong with `query.where(i => !exluded.Contains(i.Name))`?
Jamiec
last i checked EF does not support contains. Also it is just an example, very often you only want to use those filters that have a value, so it becomes if(foo!=null)(query=query.where(x=>x.foo==foo)
Andrey
@Jamiec: If `Contains` is supported then it is certainly fine. However composing `Where` clauses is more general approach - you can use it to express more general conditions.
Tomas Petricek
@Andrey, @Thomas: `Contains` is supported in EF 4, but not EF 1.
Craig Stuntz