skip to content

IQueryable and Expression Trees

IQueryable builds an expression tree that a provider translates, while IEnumerable runs delegates in memory. Interviewers ask which part of a query leaves the process.

on this pageshow

questions

6

In C#, what is the difference between calling Where on an IEnumerable<T> and on an IQueryable<T>, and where does each filter run?

level: middleimportance: must knowfreq 80%

answer

  1. two interfaces, two operator classes
  2. Enumerable vs Queryable extension methods
  3. delegate vs expression tree argument
  4. Expression and Provider properties

basics

~20 s

Where on an IEnumerable<T> binds Enumerable.Where: the lambda becomes a Func delegate that filters each item in memory. Where on an IQueryable<T> binds Queryable.Where: the lambda becomes an expression tree that the source's query provider executes, often in another process.

solid answer

~40 s

Both are LINQ sources, and `IQueryable<T>` even derives from `IEnumerable<T>`, but the compiler binds a different `Where` for each. On an `IEnumerable<T>` it picks `Enumerable.Where(Func<TSource, bool>)`, so the lambda compiles to a delegate that runs in your process, item by item, when the query is enumerated. On an `IQueryable<T>` it picks `Queryable.Where(Expression<Func<TSource, bool>>)`, so the lambda becomes an expression tree; `Queryable.Where` only adds a call node to the query's `Expression` and asks its `Provider` for a new query. When the query is enumerated, the provider gets the whole tree: a database provider translates it into its own query language, while the `EnumerableQuery<T>` that `AsQueryable()` returns runs it in memory. The declared type you hold decides which side you are on, not the runtime object.

code

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

List<Order> orders = [new(1, 250m, "Shipped"), new(2, 40m, "Open"), new(3, 900m, "Open")];
IQueryable<Order> source = orders.AsQueryable();

Func<Order, bool> asDelegate = o => o.Total > 100m;
Expression<Func<Order, bool>> asTree = o => o.Total > 100m;

var viaDelegate = source.Where(asDelegate);   // binds Enumerable.Where
var viaTree = source.Where(asTree);           // binds Queryable.Where

Console.WriteLine(viaDelegate is IQueryable<Order>);   // False
Console.WriteLine(viaTree is IQueryable<Order>);       // True
Console.WriteLine(viaTree.Expression);
// System.Collections.Generic.List`1[Order].Where(o => (o.Total > 100))

record Order(int Id, decimal Total, string Status);

go deeper

for a junior

Recall that LINQ over a list runs in your process, while LINQ over an IQueryable<T> builds a query that something else executes. Name the two classes, Enumerable and Queryable.

for a middle

Explain the binding: the declared type picks Enumerable.Where with a Func or Queryable.Where with an Expression, and IQueryable exposes Expression, Provider and ElementType so a provider can run the whole tree.

for a senior

Show you can spot the silent switch in a pull request: an IQueryable<T> typed as IEnumerable<T>, or a Func passed to Where, moves every later operator into memory without a compile error.

for a principal

Connect the mechanism to API design: an IQueryable<T> in a signature hands callers the power to shape a query that runs elsewhere, which is the starting point of any rule about where IQueryable may travel.

## Two interfaces, two sets of operators LINQ's standard query operators exist twice in the base class library. **`System.Linq.Enumerable`** holds extension methods on `IEnumerable<T>` that take delegates such as `Func<TSource, bool>`. **`System.Linq.Queryable`** holds extension methods on `IQueryable<T>` that take the same lambdas as `Expression<Func<TSource, bool>>`. The two classes mirror each other: `Where`, `Select`, `OrderBy`, `GroupBy`, `Count` and the rest exist on both with the same names, so the same query text compiles against either kind of source. | | `IEnumerable<T>` source | `IQueryable<T>` source | |---|---|---| | Extension class | `Enumerable` | `Queryable` | | `Where` parameter | `Func<TSource, bool>` | `Expression<Func<TSource, bool>>` | | What the lambda becomes | a delegate (compiled code) | an expression tree (data) | | Who runs the filter | LINQ to Objects, in your process | the source's `IQueryProvider` | | When it runs | when the query is enumerated | when the query is enumerated or executed | ## What an IQueryable<T> carries `IQueryable<T>` derives from `IEnumerable<T>` and from the non-generic `IQueryable`, which adds three read-only properties: - **`Expression`**: the expression tree that describes the query built so far. - **`Provider`**: an `IQueryProvider`, the object that builds new queries from a tree (`CreateQuery<TElement>`) and runs one (`Execute<TResult>`). - **`ElementType`**: the `System.Type` of the elements the query returns. Calling `Queryable.Where` does not filter anything. It wraps the previous tree and your quoted lambda in a method-call node for `Queryable.Where` and passes the new tree to `Provider.CreateQuery`. Each further operator grows the same tree, so by the time you enumerate, the provider sees the whole query at once. ## Where the work happens 1. You write `source.Where(o => o.Total > 100m)`. 2. The compiler looks at the **declared type** of `source`. For `IEnumerable<Order>` only `Enumerable.Where` is applicable. For `IQueryable<Order>` both are, and `Queryable.Where` wins because its receiver parameter matches the argument exactly. 3. The lambda is converted to whatever that method's parameter needs: a delegate for `Enumerable.Where`, an expression tree for `Queryable.Where`. 4. On `foreach`, `ToList()` or `Count()`, LINQ to Objects calls your delegate once per item. A queryable source instead hands its `Expression` to its provider, which translates or interprets it. For a database-backed provider this usually means the filter becomes part of a query the database runs, so only matching rows come back. How a given provider turns a tree into its own query language is that provider's subject; the C# side of the story ends when the tree is handed over. ## The declared type decides - Overload resolution happens at compile time, so the variable's declared type matters, not the object behind it. An `IQueryable<Order>` stored in an `IEnumerable<Order>` variable silently switches every later operator to `Enumerable`, and the provider never sees those filters. - `Queryable` has no overload that takes a plain delegate. Passing an existing `Func<Order, bool>` variable to `Where` on an `IQueryable<Order>` therefore binds `Enumerable.Where`, and the result is no longer an `IQueryable<Order>`. - Query syntax follows the same rules: `from o in source where o.Total > 100m select o` is first rewritten into method calls, then bound like any other call. ## An in-memory IQueryable<T> `Queryable.AsQueryable()` on a `List<T>` returns an `EnumerableQuery<T>`, whose provider runs the tree in memory with LINQ to Objects. That is why a unit test over `AsQueryable()` accepts lambdas a database provider might reject: any C# the compiler turned into a tree can run in memory. The trimming and Native AOT analyzers also flag `AsQueryable` (warnings IL2026 and IL3050), because running such a tree in memory may need code the trimmer removed or code generated at run time. ## Checking which side a query is on When a query's behaviour is in doubt, three quick checks settle it: - **The declared type** of each intermediate variable and method return: every `IEnumerable<T>` in the chain is a point where later operators leave the provider. - **`query is IQueryable<T>`** at run time: `false` after an operator bound to `Enumerable`. - **`query.Expression.ToString()`**: every operator meant for the provider must appear in the printed tree; an operator missing from it ran, or will run, in memory. ## What to say in an interview Name the two classes, the two parameter types and the consequence: with `IEnumerable<T>` your code filters; with `IQueryable<T>` your code describes the filter and the provider executes it. Then add the trap that catches people in code review: the declared type, not the runtime object, decides which side a query is on.

  • Why does Queryable.Where win over Enumerable.Where when the source is declared as IQueryable<T>?
    Both are applicable: an `IQueryable<T>` is an `IEnumerable<T>`, and a lambda converts to both `Func<T, bool>` and `Expression<Func<T, bool>>`. The lambda conversions tie, so overload resolution decides on the receiver: an identity conversion to `IQueryable<TSource>` beats an implicit reference conversion to `IEnumerable<TSource>`. If the argument is an existing `Func` variable, `Queryable.Where` is not applicable at all and `Enumerable.Where` binds.
  • Does a query over IQueryable<T> run when Queryable.Where is called?
    No. `Queryable.Where` builds a new tree and calls `Provider.CreateQuery`, which returns another query object. The provider does its real work when the query is enumerated, or when an operator that returns a single value, such as `Count` or `First`, calls `Provider.Execute` with the tree.
  • Is LINQ over List<T>.AsQueryable() a fair stand-in for a database provider in unit tests?
    Only for the logic. `EnumerableQuery<T>` runs any tree in memory, so it never rejects a method call a real provider cannot translate, and comparisons, string matching and null handling follow C# semantics rather than the database's. Test the query logic in memory, and cover translation against the real provider in an integration test.

  • IQueryable<T> and IEnumerable<T> are unrelated interfaces with separate query methods
  • Calling Where on an IQueryable<T> immediately sends a query to the data source
  • The runtime object decides which Where runs, whatever the variable's declared type is
  • Enumerable.Where and Queryable.Where both take a plain Func<T, bool>
  • AsQueryable() on a List<T> makes the filter run in a database
open as a page

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%

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.

open as a page

In C#, what does the compiler produce when the same lambda is assigned to a Func<Order, bool> and to an Expression<Func<Order, bool>>?

level: middleimportance: should knowfreq 58%

basics

~20 s

Assigned to Func<Order, bool>, the lambda compiles to a method you call through a delegate. Assigned to Expression<Func<Order, bool>>, the compiler emits code that builds a tree describing the lambda: data you inspect, translate or Compile() into a delegate.

open as a page

In C#, what do AsEnumerable() and AsQueryable() change about a LINQ query, and where do you put AsEnumerable when a provider cannot translate one of your methods?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Neither copies data or runs the query; each changes which operators bind next. Operators after AsEnumerable() run in memory, everything before stays in the provider's tree. Place it after the last step the provider can handle, just before the untranslatable call.

open as a page

In C#, how do you build an Expression<Func<Order, bool>> filter at run time with the Expression factory methods, and why does joining two lambdas' bodies fail at Compile()?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Create one ParameterExpression, build nodes with Expression.Property, Constant, GreaterThan and AndAlso, then wrap them with Expression.Lambda<Func<Order, bool>>. Joining two compiler-made lambdas' bodies fails because each refers to its own parameter object, so one is unbound.

open as a page

Should a C# repository or service return IQueryable<T> to its callers, and what rule would you set for your team about where IQueryable may travel?

level: principalimportance: should knowfreq 50%

basics

~20 s

Returning IQueryable<T> lets callers compose filters and paging the provider runs, but hands them an unexecuted query whose cost, failures and lifetime the data layer no longer controls. Most teams keep it inside the data layer.

open as a page