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

Composition Strategies

In this section, we describe three strategies for building more complex queries:

  • Progressive query construction

  • Using the into keyword

  • Wrapping queries

All are chaining strategies and produce identical runtime queries.

Progressive Query Building

At the start of the chapter, we demonstrated how you could build a lambda query progressively:

	var filtered = names.Where (n => n.Contains ("a"));
	var sorted = filtered.OrderBy (n => n);
	var query = sorted.Select (n => n.ToUpper());

Because each of the participating query operators returns a decorator sequence, the resultant query is the same chain or layering of decorators that you would get from a single-expression query. There are a couple of potential benefits, however, to building queries progressively:

  • It can make queries easier to write.

  • You can add query operators conditionally.

A progressive approach is often useful in comprehension queries. To illustrate, imagine we wanted to use Regex to remove all vowels from a list of names, and then present in alphabetical order those whose length is still more than two characters. In lambda syntax, we could write this query as a single expression—by projecting before we filter:

	IEnumerable<string> query = names
	  .Select  (n => Regex.Replace (n, "[aeiou]", ""))
	  .Where   (n => n.Length > 2)
	  .OrderBy (n => n);

	RESULT: { "Dck", "Hrry", "Mry" }

Translating this directly to comprehension syntax is trouble-some because comprehension clauses must appear in where-orderby-select order to be ...

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