Composition Strategies
In this section, we describe three strategies for building more complex queries:
Progressive query construction
Using the
into
keywordWrapping 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 ...
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.