CodeBlanks Logo Icon CodeBlanks

where in query

C# course · Advanced · Lesson 32/83

Learn where in query syntax.

where in a query

In query syntax, where filters elements. It comes after from and before select. The predicate is a bool expression over the range variable: from n in numbers where n > 3 select n.

Multiple conditions can be joined with && and ||. Only elements that satisfy the predicate proceed in the query. You can write multiple where clauses; other clauses may appear between them.

The predicate expression

where takes any bool expression over the range variable. It can be a comparison (n > 3), a method call (n.IsValid()) or a combination.

Join two predicates with && to keep elements that satisfy both; with || to keep elements that satisfy either. Parentheses set precedence: where (n > 0 && n < 10) || n == 100.

Exercise Filter even numbers with where

Filter even numbers in the numbers array using where n % 2 == 0. Iterate with foreach and print each element with Console.WriteLine(n).

Show example solution
Write from n in numbers where n % 2 == 0 select n;. Then loop with foreach (var n in query) { Console.WriteLine(n); }.
Example solution:
using System;
using System.Linq;

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

Test yourself

  1. Complete the where clause

    var query = from n in numbers ____ n > 3 select n;
    Show answer
    var query = from n in numbers where n > 3 select n;
  2. Which is a valid where usage?

    from n in numbers where n > 0 select n
    • from n in numbers where n > 0
    • where n > 0 from n in numbers select n
    • from n in numbers where n > 0 select n
    • from n in numbers select n where n > 0
    Show answer

    from n in numbers where n > 0 select n — Correct. where comes after from and before select.

  3. Match the clause to its position

    from
    First (start)
    where
    Predicate (filter)
    orderby
    Middle (sort)
    select
    Last (projection)

All lessons in Advanced