Enumerable.Where Method

Filters a sequence based on a predicate.

System.Linq
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)

Parameters

IEnumerable<TSource> source

An IEnumerable<TSource> whose elements to filter.

Func<TSource, bool> predicate

A function to test each source element for a condition.

Returns

IEnumerable<TSource>

An IEnumerable<TSource> that contains elements from the input sequence that satisfy the condition.

Remarks

The Where extension method enables you to query an IEnumerable<TSource> collection and return only the elements that match a specified condition. This method is implemented using deferred execution.

The predicate function takes an element of the source sequence as input and returns a bool value indicating whether the element should be included in the result.

If the source sequence is empty, Where returns an empty sequence.

If the predicate is null, a ArgumentNullException is thrown.

Example

using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main(string[] args)
    {
        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

        // Use Where to select numbers greater than 5
        IEnumerable<int> numbersGreaterThan5 = numbers.Where(n => n > 5);

        Console.WriteLine("Numbers greater than 5:");
        foreach (int number in numbersGreaterThan5)
        {
            Console.Write(number + " ");
        }
        // Output: Numbers greater than 5: 9 8 6 7
    }
}

See Also

Enumerable Class

IEnumerable<T> Interface

Func<T, bool> Delegate