Subodh Chettri
Subodh Chettri

Reputation: 599

What's the difference between these two statements?

List<int> result1 = 
        (from number in list where number < 3 select number).ToList();

List<int> result2 = list.Where(n => n<3).ToList();

What's the difference between these two different statements?

Upvotes: 1

Views: 145

Answers (4)

BrokenGlass
BrokenGlass

Reputation: 160922

The first notation is usually called "query syntax", the second one "method syntax" (or dot notation, or lambda syntax) - both are compiled down to exactly the same code, but as already mentioned usually one of the two is more succinct, for most scenarios this is the dot notation but especially for joining or grouping over multiple enumerations query syntax really shines.

Also check out LINQ Query Syntax versus Method Syntax (C#):

Most queries in the introductory LINQ documentation are written as query expressions by using the declarative query syntax introduced in C# 3.0. However, the .NET common language runtime (CLR) has no notion of query syntax in itself. Therefore, at compile time, query expressions are translated to something that the CLR does understand: method calls. These methods are called the standard query operators, and they have names such as Where, Select, GroupBy, Join, Max, Average, and so on. You can call them directly by using method syntax instead of query syntax.

In general, we recommend query syntax because it is usually simpler and more readable; however there is no semantic difference between method syntax and query syntax.

Upvotes: 3

CallMeLaNN
CallMeLaNN

Reputation: 8578

You notice already the first is LINQ notation and the second one uses extension method with lambda. Use the second for less code maintainance. but if you think the similarity of internal code or performance, simply use stop watch and run this code 100000 times and choose the fastest one. If the compiled code is similar, you will get the time almost the same.

Upvotes: 0

Tejs
Tejs

Reputation: 41246

There is no difference. One is just a language extension that looks similar to SQL instead of using delegates to achieve the same result.

Upvotes: 3

user541686
user541686

Reputation: 210525

Nothing.

The first one uses LINQ notation, while the second one uses extension method notation -- they both do the same thing.

Use whatever looks more pleasing to you. :)

Upvotes: 3

Related Questions