Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

c# - Difference between Query Expression and Method Expression in LINQ?

I don't know whether the term of above title is appropriate.

Just like a and b:

var list = Enumerable.Range(0, 100);

var a = from l in list
        where l % 2 == 0
        select l;
var b = list.Where(l => l % 2 == 0);

When should I use each of them? And any difference?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

None, Query expression compiles into Method expression.

Query Syntax and Method Syntax in LINQ (C#)

Because queries return an IEnumerable, you compose them in method syntax by chaining the method calls together. This is what the compiler does behind the scenes when you write queries by using query syntax

Also see: LINQ Query Expressions (C# Programming Guide)

At compile time, query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C# specification. Any query that can be expressed by using query syntax can also be expressed by using method syntax. However, in most cases query syntax is more readable and concise. For more information, see C# Language Specification and Standard Query Operators Overview.

Apart from that one place where I have found something that can't be done in Query expression is to get the index along with the item. For example you can do following in method syntax:

var result = list.Select((r,i) => new { value = r, index = i});

In query expression an external variable has to be defined to achieve this purpose. Here is a similar discussion with answer from Jon Skeet


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...