Composition Strategies
In this section, we describe three strategies for building more complex queries:
Progressive query construction
Using the
intokeywordWrapping 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access