Subqueries
A subquery is a query contained within another query’s lambda expression. The following example uses a subquery to sort musicians by their last name:
string[] musos =
{ "David Gilmour","Roger Waters", "Rick Wright" };
IEnumerable<string> query =
musos.OrderBy (m => m.Split().Last());m.Split converts each string
into a collection of words, upon which we then call the Last query operator. Last is the subquery; query references the outer
query.
Subqueries are permitted because you can put any valid C# expression on the right side of a lambda. A subquery is simply another C# expression, meaning that the rules for subqueries are a consequence of the rules for lambda expressions (and the behavior of query operators in general).
A subquery is privately scoped to the enclosing expression and is able to reference the outer lambda argument (or iteration variable in comprehension syntax).
Last is a very simple subquery.
The next query retrieves all strings in an array whose length matches
that of the shortest string:
string[] names = { "Tom","Dick","Harry","Mary","Jay" };
IEnumerable<string> outerQuery = names
.Where (n => n.Length ==
names.OrderBy (n2 => n2.Length)
.Select (n2 => n2.Length).First( )
);
// RESULT: Tom, JayHere’s the same thing in comprehension syntax:
IEnumerable<string> comprehension = from n in names where n.Length ==(from n2 in namesorderby n2.Lengthselect n2.Length).First( )select n;
Because the outer iteration variable (n) is in scope for a subquery, we cannot ...
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