Lambda Queries
Lambda queries are the most flexible and fundamental. In this section, we describe how to chain operators to form more complex queries and introduce several new query operators.
Chaining Query Operators
To build more complex queries, you add additional query operators, creating a chain. For example, the following query extracts all strings containing the letter a, sorts them by length, and then converts the results to uppercase:
string[] names = { "Tom","Dick","Harry","Mary","Jay" }; IEnumerable<string> query = names .Where (n => n.Contains ("a")) .OrderBy (n => n.Length) .Select (n => n.ToUpper( )); foreach (string name in query) Console.Write (name + "|"); // RESULT: JAY|MARY|HARRY|
Where, OrderBy
, and Select
are all standard query operators that resolve to extension
methods in the Enumerable
class.
We already introduced the Where
operator, which emits a filtered
version of the input sequence. The OrderBy
operator emits a sorted version of
its input sequence; the Select
method emits a sequence where each input element is transformed or
projected with a given lambda expression (n.ToUpper()
, in this case). Data flows from
left to right through the chain of operators, so the data is first
filtered, then sorted, then projected.
Note
A query operator never alters the input sequence; instead, it returns a new sequence. This is consistent with the functional programming paradigm, from which LINQ was inspired.
Here are the signatures of each of these extension methods (with the ...
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.