Comprehension Queries

C# provides a syntactic shortcut for writing LINQ queries, called query comprehension syntax, or simply query syntax.

In the preceding section, we wrote a query to extract strings containing the letter a, sorted by length, and converted to uppercase. Here’s the same query in comprehension syntax:

	string[] names = { "Tom","Dick","Harry","Mary","Jay" };

	IEnumerable<string> query =
	  from    n in names
	  where   n.Contains ("a")  // Filter elements
	 orderby n.Length          // Sort elements
	  select  n.ToUpper( );     // Project each element

	  foreach (string name in query)
	    Console.Write (name + "/");


A comprehension query always starts with a from clause and ends with either a select or group clause. The from clause declares an iteration variable (in this case, n), which you can think of as traversing the input collection—rather like foreach. Figure 1-2 illustrates the complete syntax.

Query comprehension syntax

Figure 1-2. Query comprehension syntax

The compiler processes comprehension queries by translating them to lambda syntax. It does this in a fairly mechanical fashion—much like it translates foreach statements into calls to GetEnumerator and MoveNext. This means that anything you can write in comprehension syntax you can also write in lambda syntax. The compiler translates our example query into the following:

	IEnumerable<string> query = names
	  .Where   (n => n.Contains ("a"))
	  .OrderBy (n ...

Get LINQ Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.