LINQ query syntax and query expression

With built-in LINQ extension methods and lambda expressions, Visual Studio allows us to write SQL-like statements in C# when invoking these methods. The syntax of these statements is called LINQ query syntax and the expression in query syntax is called a query expression.

For example, we can change the following statement:

var veges6 = products.Where(p => p.ProductName.Contains("vegetable"));

To the following query statement by using the LINQ query syntax:

var veges7 = from p in products
             where p.ProductName.Contains("vegetable")
             select p;

In the above C# statement, we can directly use the SQL keywords select, from, and where to "query" an in-memory collection list. In addition to the in-memory collection lists, we can use the same syntax to manipulate data in XML files, in the dataset, and in the database. In the following chapters, we will see how to query a database, using LINQ to Entities.

Combined with the anonymous datatype, we can shape the result of the query in the following statement:

var candyOrVeges = from p in products
                   where p.ProductName.Contains("candy") 
                         || p.ProductName.Contains("vegetable")
                   orderby p.UnitPrice descending, p.ProductID
                   select new { p.ProductName, p.UnitPrice };

As you have seen, the query syntax is a very convenient, declarative shorthand for expressing queries using the standard LINQ query operators. It offers a syntax that increases the readability and clarity of expressing queries in code and is easy to read and write correctly.

Not only is query syntax easy to read and write, Visual Studio actually provides complete IntelliSense and compile-time checking support for the query syntax. For example, when typing in p and the following dot, we get all of the Product members listed in the IntelliSense list, as shown in the following screenshot:

LINQ query syntax and query expression

If there is a typing mistake in the syntax (as is the case in the where p.productName.Contains("vegetable") statement), the compiler will tell you exactly where the mistake is and why it is wrong. There won't be any runtime error such as invalid SQL statement. The following screenshot shows the error message when there is a typing mistake in the statement:

LINQ query syntax and query expression

As you can see, you can write a LINQ statement in the query syntax, much like when you are working with a database in Query Analyzer. However, the .NET Common Language Runtime (CLR) has no notion itself of the query syntax. Therefore, at compile time, query expressions are translated to something that the CLR does understand—method calls. Under the cover, the compiler takes the query syntax expressions and translates them into explicit method-invocation code that utilizes the LINQ extension method and lambda expression language features in C#.

For example, the candyOrVeges query expression will be translated to the following method invocation call:

var candyOrVeges2 = products.Where(p => p.ProductName.Contains("candy") || p.ProductName.Contains("vegetable")).OrderByDescending(p => p.UnitPrice).ThenBy(p=>p.ProductID).Select(p=>new { p.ProductName, p.UnitPrice });

You can print out and compare the results of using query syntax and method syntax to make sure they are equivalent. The following statements will print out the product name and unit price for the products in the query result, using query syntax:

foreach (var p in candyOrVeges)
{
     Console.WriteLine("{0} {1}", p.ProductName, p.UnitPrice);
}

Do the same for the results using method syntax and you will get a printout as shown in the following screenshot:

LINQ query syntax and query expression

In general, query syntax is recommended over method syntax because it is usually simpler and more readable. However, there is no semantic difference between method syntax and query syntax.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset