Filter a LINQ sequence by a set of allowed keys

To select items whose keys belong to an allowed set, express membership with Contains. For an in-memory sequence, a HashSet<T> makes repeated membership checks efficient.

For a database query, the provider translates the expression. Keep the source as IQueryable until the intended filters are composed, and inspect the provider's generated SQL when performance matters.

Run an in-memory example

Replace Program.cs in a .NET console project:

C#
var allowedIds = new HashSet<int> { 2, 4 };
var items = new[] { new Item(1, "One"), new Item(2, "Two"), new Item(4, "Four") };
var names = items.Where(x => allowedIds.Contains(x.Id)).Select(x => x.Name);
Console.WriteLine(string.Join(", ", names));

public sealed record Item(int Id, string Name);

Run dotnet run. Expect Two, Four. An empty set selects nothing.

Apply the same intent to EF Core

With an existing context, a query such as db.Items.Where(x => ids.Contains(x.Id)) expresses membership without constructing SQL text. Providers can translate parameter collections differently across versions. Do not assume every query becomes a literal SQL IN (...) list.

Very large key collections need a measured strategy such as a staging table or provider-supported bulk input. Calling ToList() before filtering moves the work into memory and may retrieve far more rows than needed. For text membership, choose the comparer for in-memory sets and understand the database collation for server queries. They are separate comparison rules.

Official references

Enumerable.Contains Method (System.Linq)
Determines whether a sequence contains a specified element.
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.contains
Enumerable.Contains
Querying Data - EF Core
Overview of information on querying in Entity Framework Core
https://learn.microsoft.com/en-us/ef/core/querying/
EF Core querying

Author: Herman Schoenfeld