LINQ Query Syntax and Method Syntax - Part 11

This is eleventh part of the ‘LINQ’ series posts that I have started from here. In the last post you learnt how to perform calculations in LINQ query. Now, in this post you will look at some differences between LINQ Query Syntax and Method Syntax used in LINQ.

All the queries we learned in this series so far are known as LINQ Query Syntax that was introduced with 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 how to use method syntax in queries and in query expressions themselves. [Source: MSDN]

Let’s look at the example, which will produce 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 above code, you will get following output:

Query Syntax
2  4  6  8  10
Method Syntax
2  4  6  8  10

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

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

Comments

Popular posts from this blog