skip to content

A C# repository method takes a Func<Order, bool> filter and calls Where on its IQueryable<Order> source; why does the whole source get pulled into memory, and what is the fix?

level: seniorimportance: must knowfreq 65%

answer

  1. decided at compile time
  2. no Queryable overload for a delegate
  3. the result is only IEnumerable now
  4. change the parameter type

basics

~20 s

Queryable.Where takes only Expression<Func<Order, bool>>, so a Func argument binds Enumerable.Where: the provider runs the unfiltered source and the delegate filters every item in memory. Take Expression<Func<Order, bool>> instead, so the filter joins the provider's tree.

solid answer

~40 s

It is an overload-resolution problem, not a provider bug. `Queryable.Where` has no overload for a delegate, and a `Func<Order, bool>` value cannot convert to an expression tree, so the only applicable method is `Enumerable.Where`, which accepts the `IQueryable<Order>` because it is an `IEnumerable<Order>`. The result is a LINQ to Objects iterator: when it is enumerated it enumerates the source query with no filter in its tree, so the provider returns everything and the delegate discards most of it in your process. The fix is to make the parameter `Expression<Func<Order, bool>>`; lambda call sites compile unchanged and the filter becomes part of the query the provider runs. For an in-memory list the same expression still works: `Compile()` it once and pass the delegate.

code

csharp · 25 lines
csharp
using System.Linq.Expressions;

IQueryable<Order> table = new List<Order>
{
    new(1, 250m, "Shipped"), new(2, 40m, "Open"), new(3, 900m, "Open")
}.AsQueryable();
var repo = new OrderRepository(table);

var slow = repo.FindSlow(o => o.Total > 100m);
Console.WriteLine(slow is IQueryable<Order>);   // False: Enumerable.Where bound

var fast = repo.Find(o => o.Total > 100m);
Console.WriteLine(fast.Expression);             // the filter is in the tree

// The same filter on an in-memory list: compile it once to a delegate
Expression<Func<Order, bool>> filter = o => o.Total > 100m;
List<Order> cached = [new(4, 120m, "Open")];
Console.WriteLine(cached.Where(filter.Compile()).Count());   // 1

class OrderRepository(IQueryable<Order> orders)
{
    public IEnumerable<Order> FindSlow(Func<Order, bool> filter) => orders.Where(filter);
    public IQueryable<Order> Find(Expression<Func<Order, bool>> filter) => orders.Where(filter);
}
record Order(int Id, decimal Total, string Status);

go deeper

for a junior

Remember the rule behind this bug: Queryable.Where only accepts an Expression<Func<T, bool>>, so a Func argument quietly binds Enumerable.Where instead.

for a middle

Walk through the overload resolution: why Queryable.Where is not applicable to a delegate, why Enumerable.Where accepts an IQueryable, and what the returned iterator enumerates.

for a senior

Diagnose it from evidence: check whether the result is still IQueryable, print the Expression, read the provider's log, then change the parameter and let CS1503 find the callers passing delegates.

for a principal

Turn the fix into a team habit: data-access methods take expression filters or named query methods, and a Func parameter or an IEnumerable return over an IQueryable gets questioned in review.

## The symptom A repository exposes `IEnumerable<Order> Find(Func<Order, bool> filter) => orders.Where(filter);`, where `orders` is an `IQueryable<Order>` backed by a remote store. Every call returns the right orders, the tests over an in-memory list pass, and yet in production each call is slow and memory-hungry: the store returns the entire set and the filter runs afterwards. Nothing in the code looks wrong, and the compiler reports nothing. ## Why it compiles: the binding, step by step 1. `orders.Where(filter)` has two candidate extension methods named `Where` in `System.Linq`. 2. `Queryable.Where<TSource>(IQueryable<TSource>, Expression<Func<TSource, bool>>)` is **not applicable**: `filter` is a delegate value, and a delegate never converts to an expression tree (only lambda syntax does). 3. `Enumerable.Where<TSource>(IEnumerable<TSource>, Func<TSource, bool>)` **is applicable**, because `IQueryable<Order>` derives from `IEnumerable<Order>`. 4. The compiler binds `Enumerable.Where`. The return type is `IEnumerable<Order>`, and the method's declared return type hides the change, because it said `IEnumerable<Order>` all along. ## What the provider sees - The object `Enumerable.Where` returns is a LINQ to Objects iterator wrapping the `IQueryable<Order>` source. - When the caller enumerates it, the iterator enumerates the source. The source's `Expression` is the bare query with **no filter node**, so the provider fetches every element. - Each element is then passed to the delegate in your process, and most are discarded. - Any operator the caller adds afterwards (`Take`, `OrderBy`, `Count`) also binds `Enumerable`, so paging and counting happen in memory too. ## The fix | Parameter type | `Where` that binds | Where the filter runs | |---|---|---| | `Func<Order, bool>` | `Enumerable.Where` | in memory, after a full fetch | | `Expression<Func<Order, bool>>` | `Queryable.Where` | inside the provider's query | - Declare the parameter as **`Expression<Func<Order, bool>>`**. Call sites that pass a lambda, `repo.Find(o => o.Total > 100m)`, compile unchanged, because a lambda converts to either type. - Call sites that pass an existing `Func` variable or a method group stop compiling with CS1503. That is useful: each one marks a place that was never going to be filtered by the provider. - Decide what the method returns. Returning `IQueryable<Order>` keeps the query composable; materialising inside the repository with `ToList()` keeps execution there. Either way, the filter is now in the tree. - If the same filter also runs against an in-memory `List<Order>` (a cache, a test fixture), **compile it once**: `Func<Order, bool> test = filter.Compile();` and pass the delegate to `Enumerable.Where`. Going through `list.AsQueryable().Where(filter)` also works, but every enumeration then has to process the tree again; in one JIT-compiled run on .NET 10, two thousand counts over a thousand items took about 5 ms with a cached compiled delegate and about 830 ms through `AsQueryable()`. ## How to catch it 1. Check the type of the value `Where` returns: `result is IQueryable<Order>` is `false` when the delegate overload bound. 2. Print `query.Expression` before execution. A filter that should be in the query must appear there as a `Where` call. 3. Watch what the provider actually runs, through its logging, and compare the item count fetched with the count returned. 4. Treat `Func<T, bool>` parameters on data-access methods as a review smell, and the declared return type `IEnumerable<T>` on a method built from an `IQueryable<T>` as a reason to look twice. A variant of the same bug hides in helpers that take a predicate for reuse, for example a `static Func<Order, bool> IsOverdue` field shared by the API layer and the data layer. It reads well and works everywhere, but on a queryable source every use binds `Enumerable.Where`. Declaring the shared rule as `static readonly Expression<Func<Order, bool>> IsOverdue` keeps it usable in both places: pass it straight to `Queryable.Where`, and use a cached `IsOverdue.Compile()` result for in-memory lists. The same trap appears without a parameter: a helper typed `IEnumerable<Order> Open(IEnumerable<Order> source) => source.Where(o => o.Status == "Open");` binds `Enumerable.Where` even when it is given an `IQueryable<Order>`, because the declared parameter type, not the argument's object, chose the overload.

  • Does changing the parameter from Func<Order, bool> to Expression<Func<Order, bool>> break existing callers?
    Callers passing a lambda recompile unchanged, because a lambda converts to either type. Callers passing a `Func` variable or a method group fail with CS1503, since neither converts to an expression tree. Each failure points at a filter that was never reaching the provider, so rewrite it as a lambda over translatable members.
  • The repository returns IEnumerable<Order> but builds the query with Expression filters; does the caller's later Where run in the provider?
    No. The declared return type is `IEnumerable<Order>`, so the caller's `Where` binds `Enumerable.Where` and runs in memory on whatever the repository's query returned. The repository's own filter still ran in the provider. Return `IQueryable<Order>` only if callers are meant to extend the query; otherwise materialise inside and return a list.
  • Why did the unit tests not catch the full fetch?
    The tests ran over `List<Order>.AsQueryable()`, an `EnumerableQuery<T>` whose provider runs everything in memory anyway. Filtering before or after the fetch gives the same results, and fetching everything from a list costs almost nothing, so only the query's `Expression`, the provider's own log or a test against the real store reveals the difference.

  • Passing a Func to Where on an IQueryable<T> gets translated just like a lambda
  • The provider receives the Func and runs it next to the data
  • Calling AsQueryable() on the result of the Func-based Where pushes the filter back to the provider
  • Tests over a List<T> passing proves the query filters at the source
  • The compiler would warn if a Where call fell back to Enumerable