LINQ关键字与方法

问题描述:

我可以做到:

var something = things.Where(thing => thing.stuff == yup);
var somethingelse = something.Select(thing => thing.otherstuff);

var something = from thing in things
                where thing.stuff == yup
                select thing;
var somethingelse = from thing in something
                    select thing.otherstuff;

很显然,如果这是真实世界,那么关键字版本的doing会带来好处:

Obviously if this were real world there's the benefit with the keyword version of doing:

var somethingelse = from thing in something
                    where thing.stuff == yup
                    select thing.otherstuff;

但随后您当然可以争论自己可以做到:

But then of course you could argue that you could do:

var somethingelse = things.Where(thing => thing.stuff == yup)
                          .Select(thing => thing.otherstuff);

无论如何,问题本身:使用这些变体的利弊是什么?它们是否相同,只是语法代码方面不同?如果您将两种方法版本(即,如上的where/select)组合在一起,是否比使用关键字语法将两者组合成一行的效率低?

Anyway the question itself: what are the pros/cons to using each of these variants? Are they identical but just different syntax code-side? If you combine two method versions (i.e., where/select as above) is it less efficient than using the keyword syntax combining both into one line?

我喜欢LINQ,并且我不想失去任何可以通过使用一种或另一种类型获得某种效率的效率.

I love LINQ and I don't want to lose any efficiency where some could be gained by using one type or another.

查询语法将由编译器在第一遍转换为方法语法,然后在第二遍从该方法语法编译为IL代码.使用查询语法编写的代码与直接使用方法语法编写的代码之间,在生成的编译代码中没有 差异. (尽管并非所有方法都以查询语法表示,所以某些查询 不能在未部分或完全使用方法语法的情况下编写.)

The query syntax will be converted into the method syntax by the compiler in a first pass, and then compiled from that method syntax into IL code in a second pass. There is no difference in the resulting compiled code between code written using the query syntax verses code written directly in method syntax. (Although not all of the methods are represented in query syntax, so some queries cannot be written without partial or complete use of method syntax.)

唯一的区别是编码人员的个人喜好;您发现更容易阅读或编写的内容.

The only difference is the personal preference of the coder; what you find easier to read or write.

根据我的个人经验,某些类型的查询比另一种语法更易于阅读和/或编写,但这完全是一种观点问题,并且在不同人之间确实有所不同.在任何给定情况下,请使用您最喜欢的方式.

From my personal experiences certain types of queries are easier to read and/or write in one syntax over the other, but that's entirely a matter of opinion and does vary between people. Use whichever you're most comfortable with in any given situation.