Linh
Linh

Reputation: 1022

what is the difference between two query type in LINQ?

I have a table was named "MYTABLE". That have two columns "FIRSTNAME" and "LASTNAME". Two query below returned same result is IQueryable<MYTABLE>

dataContext.MYTABLEs.Where(f => f.FIRSTNAME == firstName && f.LASTNAME == lastName);

from t in dataContext.MYTABLEs
where t.FIRSTNAME == firstName && t.LASTNAME == lastName select t;

What is the difference? which one in the two query faster?

Upvotes: 1

Views: 238

Answers (4)

jason
jason

Reputation: 241641

These compile to identical IL. The latter is syntactic sugar for the former (i.e., the compiler just translates the query syntax to the method syntax before outputting IL).

However, there are some slight differences between the two. There are some queries that can only be expressed in the method syntax (for example, data.Count(somePredicate) or data.Max(somePredicate)).

For additional discussion on the LINQ Query Syntax versus the Method Syntax, see MSDN.

Upvotes: 2

Jermismo
Jermismo

Reputation: 230

They are exactly the same. They both compile to the same MSIL. One is just calling the methods on IQuerable and the other is using extensions added to C# to do the same thing.

Upvotes: 1

Ahmad Mageed
Ahmad Mageed

Reputation: 96487

They're both the same. You can write LINQ queries using lambda (method) syntax (the 1st approach) or query syntax (the 2nd approach). The latter is simply syntactic sugar and both get compiled to the same thing.

From the LINQ Query Syntax versus Method Syntax MSDN article:

there is no semantic difference between method syntax and query syntax. In addition, some queries, such as those that retrieve the number of elements that match a specified condition, or that retrieve the element that has the maximum value in a source sequence, can only be expressed as method calls.

A similar question can be found here.

Upvotes: 8

Kelsey
Kelsey

Reputation: 47726

They are the same and should compile down to the same code.

Upvotes: 0

Related Questions