LINQ
Uncategorized

Method Syntax vs Query Syntax in LINQ C#

For starters, LINQ queries in C# can be written in the following 2 ways.

  • Method Syntax (In this, we use a method call to express a query that retrieves the number of elements matching a specified condition.)

 

Example:

 

  • Query Syntax (It is similar to SQL (Structured Query Language) for the database but defined within the C# or VB code.)

 

Example:

 

 

Though Method Syntax is familiar and followed by most of the users, Query Syntax has many     advantages over Method Syntax. Let’s go through few scenarios.

 

Scenario 1:

Join queries can be written easily using Query syntax when compared to Method syntax and it is always preferred to write Query syntax when we need to join collections.

Example:

 

Query syntax goes something like this:

 

 

 

Method syntax goes something like this:

 

 

Output:

Employee1 : c#
Employee2: LINQ
Employee3: c#
Employee4: .Net Core
Employee5: c#
Both queries give same output but query syntax is more clear and easily understandable when compared to method syntax which looks little complicated.

 

Scenario 2:

Use Query Syntax when you have multiple data sources.

Example:

 

 

Query Syntax goes like this:

Method Syntax goes like this:

 

 Output:

cell [1, A]

cell [1, B]

cell[1,C]

cell[2,A]

cell[3.C]

 

In this case, Query Syntax looks simple and easy which uses 2 from keywords for 2 sources where as Method syntax is a bit complicated one here.

 

There are many other scenarios or flexibilities that Query Syntax provide are:

  • Query Syntax provides let It allows us to store the result and use it later in the query.

 

Example:

 

 

 

here let allows experience variable/data to be used later in the query.

 

  • Query Syntax also provides other keywords like group, orderby which can be easily used in writing LINQ queries which makes them much simpler and easily understandable.

 

 

SUMMARY

To summarize, while considering performance and output there isn’t much difference in both the syntaxes. Since we use simple queries most of the time in our code, we prefer Method syntax as we are used to writing and calling methods in the code, but in complex queries (i.e. writing joins, order by and group by etc..) and other scenarios like storing small datasets inside the query to use it further (i.e. let keyword), it is better to use Query Syntax.

About The Author