Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...