Reader Level:
ARTICLE

LINQ Query Syntax and Method Syntax: Part 11

Posted by Abhimanyu K Vatsa Articles | LINQ September 07, 2012
In this article you will look at some differences between LINQ Query Syntax and Method Syntax used in LINQ.
  • 0
  • 0
  • 6960

This is the eleventh part of the "LINQ" series of articles that I have started from here. In the previous article you learned how to perform calculations in a LINQ query. Now, in this article you will look at some differences between LINQ Query Syntax and Method Syntax used in LINQ.

All the queries we have learned in this series so far are known as LINQ Query Syntax that was introduced with the C# 3.0 release. Actually, at compile time queries are translated into something that the CLR understands. So, it makes a method call at runtime to produce standard SQL queries that uses real SQL keys like WHERE, SELECT, GROUPBY, JOIN, MAX, AVERAGE, ORDERBY and so on. So, we have a direct way to avoid such method calls to produce standard SQL and that is known as Method Syntaxes.

If you ask me, I recommend Query Syntax because it is usually simpler and more readable; however 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. The reference documentation for the standard query operators in the System.Linq namespace generally uses Method Syntax. Therefore, even when getting started writing LINQ queries, it is useful to be familiar with the use of Method Syntax in queries and in query expressions themselves. [Source: MSDN]

Let's look at the example, which will produce the same result using Query Syntax and Method Syntax.

int[] numbers = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var query1 = from num in numbers
                where (num % 2) == 0
               
select num;
var query2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n);
Console.WriteLine("Query Syntax");
foreach (int i in query1)
{
   
Console.Write(i + "  ");
}
Console.WriteLine("\nMethod Syntax");
foreach (int i in query2)
{
   
Console.Write(i + "  ");
}

If you run the above code, you will get the following output:

Query Syntax

2  4  6  8  10

Method Syntax

2  4  6  8  10

In query2, I use Method Syntax and you can see it also produced the same output. You can also see I'm using where and orderby clauses like a method and in the method I'm using Lambda syntaxes.

I hope you will find it useful. Thanks for reading.

COMMENT USING