O'Reilly logo

LINQ Pocket Reference by Joseph Albahari, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 + "/");

	// RESULT: JAY/MARY/HARRY/

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required