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, Jay
Here’s the same thing in comprehension syntax:
IEnumerable<string> comprehension = from n in names where n.Length ==(from n2 in names
orderby n2.Length
select n2.Length).First( )
select n;
Because the outer iteration variable (n
) is in scope for a subquery, we cannot ...
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.