Sweetening LINQ syntax with syntactic sugar
C# 3.0 introduced some new language keywords in 2008 to make it easier for programmers with experience with SQL to write LINQ queries. This syntactic sugar is officially called the LINQ query comprehension syntax.
Consider the following array of string
values:
string[] names = new[] { "Michael", "Pam", "Jim", "Dwight",
"Angela", "Kevin", "Toby", "Creed" };
To filter and sort the names, you could use extension methods and lambda expressions, as shown in the following code:
var query = names
.Where(name => name.Length > 4)
.OrderBy(name => name.Length)
.ThenBy(name => name);
Or you could achieve the same results by using query comprehension syntax, as shown in the following code:
var query = from name in names
where name.Length > 4
orderby name.Length, name
select name;
The compiler changes the query...