CodeBlanks Logo Icon CodeBlanks

Where

C# course · Intermediate · Lesson 89/116

Learn to filter elements matching a condition with Where.

Filtering with Where

The Where method filters a collection by a condition. The condition is a lambda expression that returns bool for each element. Elements that return true stay in the result; false ones are dropped.

Example: words.Where(w => w.Length > 4) keeps words longer than four characters. The lambda parameter (w) represents one element of the collection. The result is again an IEnumerable<string>; you can loop with foreach or materialize with .ToList().

Anatomy of a lambda

A lambda has the form parameter => expression. The left of => takes a parameter name, the right takes the return value. The lambda n => n > 5 takes n and returns the boolean n > 5.

You can also write two-parameter lambdas: (a, b) => a + b. Parentheses are required for multiple parameters. A lambda can also capture outer variables, which lets you parameterize LINQ filter conditions from outside.

Exercise Filter even numbers

Filter the even numbers from numbers with Where and print each in a foreach loop. Even: n % 2 == 0.

Show example solution
Filter with numbers.Where(n => n % 2 == 0), loop with foreach, print with Console.WriteLine(n).
Example solution:
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5, 6 };
        foreach (var n in numbers.Where(n => n % 2 == 0))
        {
            Console.WriteLine(n);
        }
    }
}

Test yourself

  1. Complete the condition

    var longWords = words.Where(w => w.____ > 4);
    Show answer
    var longWords = words.Where(w => w.Length > 4);
  2. What does Where return?

    var r = numbers.Where(n => n > 5);
    • List<int>
    • int[]
    • IEnumerable<int>
    • bool
    Show answer

    IEnumerable<int> — Correct. Where returns IEnumerable<int>; it is still a collection but evaluation is deferred.

  3. Match each lambda to its result

    n => n > 5
    true (n=8)
    n => n % 2 == 0
    true (n=4)
    n => n < 0
    false (n=3)
    n => n == 10
    true (n=10)

All lessons in Intermediate