Updated on

The LINQ Where() method filters a sequence: it keeps every element for which a predicate returns true and skips the rest. It works on in-memory collections through IEnumerable<T> and on database queries through IQueryable<T>.

To download the source code for this article, you can visit our GitHub repository.

The LINQ Where Method offers a powerful tool that can manipulate data from various sources ranging from collections of objects in memory to relational database tables and XML files according to a specific criterion. It offers a simple, intuitive syntax similar to SQL, that makes writing queries on collections easier, simpler, maintainable, and more efficient.

To know more about LINQ, read our article on LINQ Basic Concepts in C#

In C#, the where keyword also sets constraints on generic type parameters, which is a separate feature from the LINQ method we cover here.

Let’s begin!

The Signatures of the LINQ Where Extension Method

The Where() query method has two different signatures for IEnumerable<T> and two for IQueryable<T>, each accepting a collection as input and returning a subset of the original collection.

IEnumerable<T> Collections Filtering

Firstly, .NET provides a Where() method signature allowing filtering of an IEnumerable<T> collection using a predicate. The predicate takes a TSource element and returns a boolean indicating whether or not the element should be included in the filtered result:

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

Let’s use this Where() method on a collection of integers:

int[] randomNumbers = [1, 5, 23, 11, 7, 2, 9, 8, 3, 6, 4, 20, 15, 0, 18, 13, 10, 33];

var evenNumbers = randomNumbers.Where(x => x % 2 == 0).OrderBy(x => x).ToList();

We apply the filter operator here to retain only the even numbers. If we print the resulting list to the console we see:

0, 2, 4, 6, 8, 10, 18, 20

We can write the same filter in query syntax. The compiler turns the where clause into a call to the same Where() method:

var evenNumbersFromQuery = (from x in randomNumbers
                            where x % 2 == 0
                            orderby x
                            select x).ToList();

The result is the same list of even numbers.

When working with an in-memory enumerable object, Where() acts as an extension method of the IEnumerable<T> interface.

IEnumerable<T> Collection Indexed Filtering

Secondly, another Where() overload provides access to the index of the current element in the predicate as well as to the element itself:

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

As with all C# collections, the index starts at 0, not 1.

Here, we only want to keep the numbers at odd indices:

var oddNumbers = Enumerable.Range(50, 10).Where((_, index) => index % 2 != 0).ToList();

The result is:

51, 53, 55, 57, 59

IQueryable<T> Collections Filtering

The third overload of the Where() method allows filtering IQueryable<T> collections, which represent queries on a data source that may not be in memory, typically like databases. However, in this case, a lambda expression tree forms the predicate:

public static IQueryable<TSource> Where<TSource>(
    this IQueryable<TSource> source,
    Expression<Func<TSource, bool>> predicate)

Queryable has an index overload too, which takes an Expression<Func<TSource, int, bool>>. EF Core cannot translate it, so a query that uses it throws an InvalidOperationException when we enumerate it.

Refer to our article on Expression Trees in C# to learn more about them.

First of all, to illustrate this overload of the Where operator, we’ll use a database of people. In this model, a person may have zero, one or multiple pets and live in a single address:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; } = string.Empty;
    public string LastName { get; set; } = string.Empty;
    public DateTime BirthDate { get; set; }
    public Address Address { get; set; } = null!;
    public List<Pet> Pets { get; set; } = [];
}

public class Address
{
    public int Id { get; set; }
    public string Street { get; set; } = string.Empty;
    public string City { get; set; } = string.Empty;
    public string ZipCode { get; set; } = string.Empty;
    public int PersonId { get; set; }
    public Person Person { get; set; } = null!;
}

public class Pet
{
    public int Id { get; set; }
    public string Breed { get; set; } = string.Empty;
    public string Name { get; set; } = string.Empty;
    public int PersonId { get; set; }
    public Person? Person { get; set; }
}

Additionally, we use Entity Framework Core with the Microsoft.EntityFrameworkCore.InMemory package to access the database. In the context class, we add data to our entities using the OnModelCreating() method:

using Microsoft.EntityFrameworkCore;

public class ApplicationContext : DbContext
{
    public ApplicationContext() {}

    public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options) { }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseInMemoryDatabase(databaseName: "PeopleDatabase");
        base.OnConfiguring(optionsBuilder);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>()
            .HasOne(p => p.Address)
            .WithOne(a => a.Person)
            .HasForeignKey<Address>(a => a.PersonId);

        // HasData() seeds four people, four addresses and three pets here
    }

    public DbSet<Person> People { get; set; }
    public DbSet<Address> Addresses { get; set; }
    public DbSet<Pet> Pets { get; set; }
}

The seed data itself is in the source code, and the in-memory database holds it only after we call context.Database.EnsureCreated(). In Program.cs, we create the context with using var context = new ApplicationContext(); and call EnsureCreated() on the next line, before the first query.

We keep every database query in a static Helper class. Each of these methods receives the context and returns a List<Person>.

Now, let’s query the database to retrieve people who were born in 1974 or later:

using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

public static class Helper
{
    public static List<Person> GetPeopleBornFrom1974(ApplicationContext context)
    {
        IQueryable<Person> queryResult = context.People.Where(p => p.BirthDate.Year >= 1974);

        return queryResult.ToList();
    }
}

Here, we obtain two persons corresponding to our request: 

JACKSON Colleen
RICHARD Dan

We can continuously add operations like OrderBy() or additional Where() clauses to the same IQueryable query. Each operation builds a new expression tree that represents the cumulative query.

The actual SQL query is not generated and sent to the database until we enumerate the IQueryable object, such as by calling ToList(). This ensures that all modifications are included in a single SQL query, and the database returns only the filtered rows.

When Does the LINQ Where Method Actually Filter?

Where() filters nothing at the moment we call it. It returns a query object that remembers the source and the predicate, and the filter runs only when something enumerates that object: a foreach loop, ToList(), ToArray(), Count() or First().

Microsoft Learn says it plainly in the method’s remarks: “The query represented by this method is not executed until the object is enumerated”.

That has two consequences we can see in code. First, the result reflects the source as it is when we enumerate, not as it was when we wrote the query. Second, every enumeration runs the filter again from the start. If we loop over the same query twice, the predicate runs twice for every element.

With IQueryable<T> the same rule applies, but the work happens somewhere else. EF Core translates the whole query when we enumerate it, so nothing reaches the database before that.

When we need a fixed snapshot, we call ToList() once and keep the list.

Let’s see it in action:

List<int> numbers = [1, 2, 3, 4];
var evens = numbers.Where(x => x % 2 == 0);

numbers.Add(6);
Console.WriteLine(string.Join(", ", evens));

numbers.Add(8);
Console.WriteLine(string.Join(", ", evens));

We add elements after the query is written, and both are in the result:

2, 4, 6
2, 4, 6, 8

If you want a refresher on the difference between the two interfaces, our article on IEnumerable and IQueryable covers it.

Examples of the LINQ Where Method in Action

Let’s look at some use cases of the LINQ Where() method.

Multiple LINQ Where Method Filtering

Firstly, it is possible to chain Where() clauses to refine the filtered data with each iteration.

Let’s gather information on people born before 1974 but who also reside in the city of Nancy, France. We add this method to Helper:

public static List<Person> GetPeopleUsingChainingWhereOperators(ApplicationContext context)
{
    IQueryable<Person> result = context.People
        .Include(person => person.Address)
        .Where(s => s.BirthDate.Year < 1974)
        .Where(s => s.Address.City.Equals("NANCY"));

    return result.ToList();
}

According to our database data, only one person meets these criteria: 

LAWRENCE Dennis

Nested LINQ Where Operators

We also have the option to include an instruction using another Where operator in the predicate of one Where operator:

public static List<Person> GetPeopleUsingNestedWhereOperators(ApplicationContext context)
{
    IQueryable<Person> peopleWithAustralianShepherd = context.People
         .Include(p => p.Pets)
         .Where(person => person.Pets.Where(pet => pet.Breed.Contains("Australian")).Any(pet => pet.Name.Equals("Naïa")));

    return peopleWithAustralianShepherd.ToList();
}

Here, the query returns:

RICHARD Dan

LINQ Where Method With an Expression as Parameter

Finally, let’s rewrite the previous LINQ query, this time using an expression as a parameter of the Where operator:

public static List<Person> GetPeopleUsingExpression(ApplicationContext context)
{
    Expression<Func<Person, bool>> hasAustralianShepherd = p => p.Pets.Any(pet => pet.Breed.Equals("Australian Shepherd") && pet.Name.Equals("Naïa"));
    var filteredResult = context.People.Where(hasAustralianShepherd);

    return filteredResult.ToList();
}

Again, our query returns:

RICHARD Dan

The variable’s type matters here. Where() picks its overload from that type, and only the Expression overload keeps the filter inside the database query.

Don’t do this when the source is a database:

public static List<Person> GetPeopleBornFrom1974OnTheClient(ApplicationContext context)
{
    Func<Person, bool> bornFrom1974 = p => p.BirthDate.Year >= 1974;
    IEnumerable<Person> result = context.People.Where(bornFrom1974);

    return result.ToList();
}

It compiles and returns the same two people. But a Func is not an expression tree, so the call binds to Enumerable.Where() instead of Queryable.Where(). EF Core loads every person from the table, and the filter runs in our process. With a relational database, the generated SQL has no WHERE clause at all.

If we try to keep the result as an IQueryable<Person>, the compiler stops us:

error CS0266: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<Person>' to 'System.Linq.IQueryable<Person>'. An explicit conversion exists (are you missing a cast?)

So when we store a predicate in a variable for a database query, we declare it as Expression<Func<Person, bool>>, as in the previous example.

Conclusion

In this article, we learned how to filter a sequence of elements according to a boolean condition with the LINQ Where Method. We looked at chaining the Where operator with other LINQ operators to create more complex queries. We also looked at the signatures of the Where operator and explored some use cases.

We also saw when the filter actually runs, and why a predicate for a database query belongs in an Expression<Func<T, bool>>. For the other filtering operator and the sorting operators, our overview of LINQ sorting and filtering picks up from here. And when the values to keep come from a second collection, see how to filter a list based on another list. If the predicate does heavy CPU work for every element of a large in-memory collection, PLINQ can spread the same Where() across the processor cores.

Tested with .NET 11 (SDK 11.0.100, runtime 11.0.0) and EF Core 11.0.0.