LINQ Where

Summary: in this tutorial, you’ll learn how to use the LINQ Where() method to filter a sequence of values based on a specified condition.

Introduction to the LINQ Where() method

LINQ Where() is an extension method that filters a sequence of values based on a condition specified by a predicate:

IEnumerable<TSource> Where<TSource> (
    this IEnumerable<TSource> source, 
    Func<TSource,bool> predicate
);Code language: C# (cs)

In this syntax:

  • TSource is the type of elements of the source sequence.
  • source is an input sequence to filter with the type of IEnumerable<T>.
  • predicate is a function that tests the element of the source against a specified condition.

The Where() method returns a new sequence with the type IEnumerable<TSource> containing elements that satisfy the condition.

Note that the Where() method uses deferred execution. It means that the return query of the Where() method is not executed until it is enumerated by either a foreach or calling its GetEnumerator() method.

LINQ Where() method example

Let’s take some examples of using the LINQ Where() method.

1) Using the Where() method to filter a sequence of number

The following example uses the Where() method to filter a sequence of integers and returns a new sequence whose elements are greater than or equal to 5:

using static System.Console;

int[] scores = { 2, 5, 7, 3, 8, 9 };

var filteredScores = scores.Where(n => n >= 5);

foreach (var score in filteredScores)
{
    WriteLine(score);
}Code language: C# (cs)

Output:

5
7
8
9Code language: plaintext (plaintext)

In this example, the Where() method filters the scores array based on the condition n >=5.

The lambda expression n => n >= 5 defines the predicate function that the Where() method uses to filter the sequence. The result is a new sequence that contains only the scores that are greater than or equal to 5.

The following example uses a more complex condition with the AND (&&) operator that filters the scores within a range:

using static System.Console;

int[] scores = { 2, 5, 7, 3, 8, 9 };

var filteredScores = scores.Where(n => n >= 5 && n <= 8);

foreach (var score in filteredScores)
{
    WriteLine(score);
}Code language: C# (cs)

Output:

5
7
8Code language: plaintext (plaintext)

In this example, the condition filters only scores that are from 5 to 8. This is equivalent to calling the Where() method twice:

using static System.Console;

int[] scores = { 2, 5, 7, 3, 8, 9 };

var filteredScores = scores.Where(n => n >= 5)
                            .Where(n => n <= 8);

foreach (var score in filteredScores)
{
    WriteLine(score);
}Code language: C# (cs)

Similarly, you can use the OR operator (||) to filter get the numbers from the scores array that are less than 5 or greater than 8:

using static System.Console;

int[] scores = { 2, 5, 7, 3, 8, 9 };

var filteredScores = scores.Where(n => n < 5 || n > 8);

foreach (var score in filteredScores)
{
    WriteLine(score);
}Code language: JavaScript (javascript)

Output:

using static System.Console;

int[] scores = { 2, 5, 7, 3, 8, 9 };

var filteredScores = scores.Where(n => n < 5 || n > 8);

foreach (var score in filteredScores)
{
    WriteLine(score);
}Code language: C# (cs)

Output:

2
3
9Code language: plaintext (plaintext)

2) Using the Where() method to filter a sequence of strings

The following example uses the Where() method to filter a list of names whose lengths are less than or equal to 3:

using static System.Console;

var names = new List<string> { "John", "Mary", "Alex", "Tim", "Joe", "Ana" };

var shortNames = names.Where(name => name.Length <= 3);

foreach (var name in shortNames)
{
    WriteLine(name);
}Code language: C# (cs)

Output:

Tim
Joe
AnaCode language: C# (cs)

In this example, we use the Where() method to filter the names list based on the condition:

name.length < 3Code language: C# (cs)

The lambda expression name => name.length < 3 defines the predicate function that the Where() method uses to filter the list.

The result is a new sequence that contains only the names whose lengths are less than or equal to 3 characters.

The output shows three names that satisfy the condition, Tim, Joe, and Ana.

3) Using the Where() method to filter a sequence of objects

The following program uses the Where() method to filter employees whose salaries are greater than 55,000 USD:

using static System.Console;

class Employee
{
    public string? Name { get; set; }
    public string? Department { get; set; }
    public int Salary { get; set; }
}
class Program
{
    public static void Main()
    {
        var employees = new List<Employee>()
        {
            new Employee { Name = "John", Department = "HR", Salary = 50000 },
            new Employee { Name = "Jane", Department = "IT", Salary = 60000 },
            new Employee { Name = "Bob", Department = "HR", Salary = 45000 },
            new Employee { Name = "Sara", Department = "IT", Salary = 55000 },
            new Employee { Name = "Tom", Department = "IT", Salary = 65000 }
        };

        var results = employees.Where(e => e.Salary > 55000);

        foreach (var employee in results)
        {
            WriteLine($"{employee.Name} - {employee.Salary:C}");
        }
    }
}
Code language: C# (cs)

Output:

Jane - $60,000.00
Tom - $65,000.00Code language: C# (cs)

Summary

  • Use the LINQ Where() method to filter a sequence of values based on a specified condition.
Was this tutorial helpful ?