Filtering Using a where Clause

Filtering elements of a sequence based on a predicate is one of the most common query operations performed. The query expression’s where clause facilitates this by use of a Boolean-valued expression that’s evaluated for each element in the sequence:

var nums = new List<int> { 1, 2, 3, 4, 5 };var evens = from n in nums            where n % 2 == 0            select n;

Internally, the where clause translates into a class to a Where query operator method, as shown here:

var evens = nums.Where(n => n % 2 == 0);

Figure 19.16 illustrates the syntactical translation that happens here, just as we did for the select clause before. It’s important to emphasize query expressions are nothing but a little syntactical veneer on ...

Get C# 4.0 Unleashed 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.