C# 3 introduced some new keywords in 2008 to make it easier for programmers with experience in SQL to write LINQ queries. This syntactic sugar is sometimes called the LINQ query comprehension syntax.
Consider the following code:
var names = new string[] { "Michael", "Pam", "Jim", "Dwight", "Angela", "Kevin", "Toby", "Creed" }; var query = names .Where(name => name.Length > 4) .OrderBy(name => name.Length) .ThenBy(name => name);
Instead of writing the preceding code using extension methods and lambda expressions, you can write the following code using query comprehension syntax:
var query = from name in names where name.Length > 4 orderby name.Length, name select name;
The compiler changes the query comprehension syntax to the extension method and lambda expression equivalent for you.
Not all extension methods have a C# keyword equivalent, for example, the Skip
and Take
extension methods that are commonly used to implement paging for lots of data. The following query cannot be written using only the query syntax:
var query = names .Where(name => name.Length > 4) .OrderBy(name => name.Length) .ThenBy(name => name) .Skip(80) .Take(10);
Luckily, you can wrap query comprehension syntax in parentheses and then switch to using extension methods, as shown in the following code:
var query = (from name in names where name.Length > 4 orderby name.Length, name select name) .Skip(80) .Take(10);
3.144.252.204