正确的LINQ的where子句 [英] Proper Linq where clauses

查看:238
本文介绍了正确的LINQ的where子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写LINQ相当数量的在我的日常生活,但大多是简单的语句。我注意到,使用where子句时,有许多方法来写他们,每个人都有相同的结果,据我可以告诉。例如;

I write a fair amount of linq in my day to day life, but mostly simple statements. I have noticed that when using where clauses, there are many ways to write them and each have the same results as far as I can tell. For example;

from x in Collection
  where x.Age == 10
  where x.Name == "Fido"
  where x.Fat == true
  select x;

显示为等同于这个至少尽可能的结果而言:

Appears to be equivalent to this at least as far as the results are concerned:

from x in Collection
  where x.Age == 10 &&
        x.Name == "Fido" &&
        x.Fat == true
  select x;

那么,有没有一个真正的差别比其他的语法?如果是这样,什么是preferred风格,为什么?

So is there really a difference other than syntax? If so, what is the preferred style and why?

推荐答案

第二个会更有效,因为它只是有一个predicate以评估对集合中的每个项目,其中在第一个,它的应用第一predicate首先所有项目和结果(这是在这一点上缩小)被用于第二predicate等。结果让每一个传球收窄,但仍然涉及到多个通行证。

The second one would be more efficient as it just has one predicate to evaluate against each item in the collection where as in the first one, it's applying the first predicate to all items first and the result (which is narrowed down at this point) is used for the second predicate and so on. The results get narrowed down every pass but still it involves multiple passes.

此外,如果你有你的AND运算predicates的链接(第一法)才有效。事情是这样的 x.Age == || 10 x.Fat ==真不会与你的第一个方法工作。

Also the chaining (first method) will work only if you are ANDing your predicates. Something like this x.Age == 10 || x.Fat == true will not work with your first method.

这篇关于正确的LINQ的where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆