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

查看:33
本文介绍了正确的 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;

那么除了语法之外真的有区别吗?如果是这样,首选的风格是什么?为什么?

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

推荐答案

第二个会更有效,因为它只有一个谓词来评估集合中的每个项目,而在第一个中,它应用第一个谓词首先到所有项目,结果(此时已缩小范围)用于第二个谓词,依此类推.每次通过都会缩小结果范围,但仍然涉及多次通过.

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 运算时才有效.类似这样的 x.Age == 10 ||x.Fat == true 不适用于您的第一种方法.

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天全站免登陆