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 ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.