简体   繁体   English

为LinqToEntities查询使用多个.Where()调用或&&条件

[英]Using multiple .Where() calls or && conditions for LinqToEntities queries

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? 有没有办法可以看到查询的sql输出?

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

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

As Andrew says, the two options are equivalent. 正如安德鲁所说,这两个选项是等价的。 One practically useful difference is that you can easily generate conditions in the Where clause programmatically. 一个实际有用的区别是您可以通过编程方式轻松地在Where子句中生成条件。 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. 使用&&运算符编写查询时,这是无法轻松完成的。

Both queries will translate to the same SQL - you can use a tool like LinqPad to verify this if you want (I just did). 两个查询都将转换为相同的SQL - 您可以使用像LinqPad这样的工具来验证这个(如果你愿意的话)。 The LINQ provider that translate your expression trees into T-SQL is smart enough to understand that these queries are synonymous. 将表达式树转换为T-SQL的LINQ提供程序足够聪明,可以理解这些查询是同义词。 Of course this means that both queries will perform equally as well. 当然,这意味着两个查询也将同样执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM