CSharp - LINQ Where


The Where operator is used to filter elements into a sequence.


Where operator has two prototypes we will cover.

public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate);

This prototype of Where takes an input source sequence and a predicate method delegate.

It returns an object that, when enumerated, enumerates through the input source sequence yielding elements for which the predicate method delegate returns true.

This is an extension method, we call the Where operator using the instance method syntax.

When calling Where, you pass a delegate to a predicate method.

Your predicate method must accept a type T as input, where T is the type of elements contained in the input sequence, and return a bool.

Where operator will call your predicate method for each element in the input sequence and pass it the element.

If your predicate method returns true, Where will yield that element into Where's output sequence.

If your predicate method returns false, it will not.

public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, int, bool> predicate);

The second Where prototype specifies that your predicate method delegate receives an additional integer input argument.

That argument will be the index number for the element from the input sequence.

The index is zero-based, so the index passed for the first element will be zero.

The last element will be passed the total number of elements minus one.


ArgumentNullException is thrown if any of the arguments are null.

The following code is an example of calling the first prototype.


using System;
using System.Linq;
using System.Collections.Generic;
class Program//ww w  .  j  a va  2 s .c o m
    static void Main(string[] args)
        string[] names = { "Python", "Java", "Javascript", "Bash", "C++", "Oracle" };

        IEnumerable<string> sequence = names.Where(p => p.StartsWith("J"));

        foreach (string s in sequence)
            Console.WriteLine("{0}", s);



In this example, we are returning only those elements that start with the string "J".

We are passing our predicate method using a lambda expression.

Related Topics