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?
answer
- the static type, nothing else
- no copy and no execution
- later operators bind Enumerable
- as late as possible
- EnumerableQuery<T> wraps a sequence
basics
~20 sNeither 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.
solid answer
~40 s`Enumerable.AsEnumerable` is literally `=> source`: it returns the same object typed as `IEnumerable<T>`, so every later operator binds to `Enumerable` and runs in your process, while everything before it stays in the `IQueryable<T>` tree. When the query is enumerated the provider executes its part and streams results into the in-memory part. The compiler accepts a call to your own static method inside a queryable lambda because it is just a method-call node; whether the provider can translate it is decided at run time. So filter, sort and project as far as the provider can, call `AsEnumerable()`, then apply the C#-only step. `Queryable.AsQueryable` goes the other way: it returns an `IQueryable<T>` source unchanged, and wraps any other sequence in an `EnumerableQuery<T>` that runs trees in memory; nothing becomes remote.
code
csharp · 20 linesList<Order> orders = [new(1, 250m, "Shipped"), new(2, 40m, "Open"), new(3, 900m, "Open")];
IQueryable<Order> source = orders.AsQueryable();
// Everything before AsEnumerable stays in the tree the provider receives
IQueryable<Order> providerPart = source.Where(o => o.Status == "Open");
Console.WriteLine(providerPart.Expression);
// System.Collections.Generic.List`1[Order].Where(o => (o.Status == "Open"))
// After AsEnumerable the static type is IEnumerable<Order>: Enumerable.Where binds
IEnumerable<Order> inMemory = providerPart.AsEnumerable().Where(o => Rules.IsPriority(o));
Console.WriteLine(inMemory is IQueryable<Order>); // False
foreach (var o in inMemory) Console.WriteLine(o.Id); // 3
// Left in the tree, the C# method becomes a node the provider must understand
IQueryable<Order> allInTree = source.Where(o => Rules.IsPriority(o));
Console.WriteLine(allInTree.Expression);
// System.Collections.Generic.List`1[Order].Where(o => IsPriority(o))
static class Rules { public static bool IsPriority(Order o) => o.Total > 500m; }
record Order(int Id, decimal Total, string Status);go deeper
Recall that AsEnumerable() switches the rest of a query to in-memory LINQ and AsQueryable() wraps a sequence as an IQueryable, without running anything.
Explain that both only change the declared type, that AsEnumerable returns its source as is, and that the provider's work stops exactly where the call sits.
Show placement judgment: push filtering, sorting and projection to the provider first, switch with AsEnumerable just before the C#-only step, and choose ToList when the result is reused.
Treat hidden IEnumerable boundaries as a design question: a team rule on where queries leave the provider makes data volume predictable and keeps provider-specific failures in one layer.
## Changing sides by changing the static type LINQ decides at compile time whether an operator is an `Enumerable` one (delegates, in memory) or a `Queryable` one (expression trees, handed to a provider), based on the declared type of the source. Two small methods exist purely to change that declared type: | Method | Declared on | Returns | What changes | |---|---|---|---| | `AsEnumerable<TSource>()` | `Enumerable` | `IEnumerable<TSource>` | later operators bind `Enumerable` | | `AsQueryable<TElement>()` | `Queryable` | `IQueryable<TElement>` | later operators bind `Queryable` | In the runtime source, `Enumerable.AsEnumerable` is the one-liner `=> source`. It copies nothing, executes nothing and allocates nothing; it is a type change you can see only in which overloads the compiler picks next. ## AsEnumerable in practice 1. Build the part of the query the provider can handle on an `IQueryable<T>`: `source.Where(o => o.Status == "Open")`. 2. Call `.AsEnumerable()`. The static type is now `IEnumerable<Order>`. 3. Apply the step only C# can do: `.Where(o => Rules.IsPriority(o))` now binds `Enumerable.Where` and compiles the lambda to a delegate. 4. Enumerate. The query is still deferred: enumerating the final sequence enumerates the queryable part, so the provider runs its tree and the in-memory operators process each result as it arrives. The provider's part ends exactly where `AsEnumerable()` sits. Everything after it, including `OrderBy`, `Take` or `Count`, runs in memory over whatever the provider returned. ## Why the compiler does not stop an untranslatable call - Inside a lambda converted to an expression tree, a call to a static method such as `Rules.IsPriority(o)` is legal; it becomes a `MethodCallExpression` naming that method. - The compiler checks only that the lambda can be expressed as a tree. It rejects a call to a **local function** (CS8110), but has no idea which methods a given provider understands. - The provider meets the node when it processes the tree, which with most providers is at execution, and fails at run time if it cannot translate it. The exception type and the exact rules belong to that provider. - An `EnumerableQuery<T>` from `AsQueryable()` runs any such tree in memory, which is why the same query can work in a unit test and fail against a real store. ## AsEnumerable compared with ToList | | `AsEnumerable()` | `ToList()` | |---|---|---| | Executes the query | no, stays deferred | yes, immediately | | Buffers results | no, streams | yes, the whole result | | Enumerating twice | runs the provider's part twice | reuses the list | Pick `AsEnumerable()` to keep streaming and deferral, `ToList()` when you need the results more than once or must finish with the source before continuing. ## AsQueryable - If the source already implements `IQueryable<T>`, `AsQueryable()` returns it unchanged. - Otherwise it wraps the sequence in an `EnumerableQuery<T>`, whose provider runs expression trees in memory with LINQ to Objects. A `List<T>` does not become a remote query. - Typical uses: satisfying an API that demands `IQueryable<T>`, test doubles, and composing dynamic trees over in-memory data. - The trimming and Native AOT analyzers flag `AsQueryable` with warnings IL2026 and IL3050, because running such trees may need trimmed code or code generated at run time. ## A worked placement Suppose a query filters open orders, sorts them by date, and must then keep only those that pass `Rules.IsPriority`, a C# method the provider cannot translate, before taking the first ten. The order of steps decides the cost: - `Where(status)`, `OrderBy(date)`, then `AsEnumerable()`, then `Where(IsPriority)` and `Take(10)`: the provider filters and sorts, and memory sees only open orders, streamed until ten pass. - `AsEnumerable()` first: the provider returns every order and sorting happens in memory too. - `Take(10)` before `AsEnumerable()`: cheaper, but it changes the answer, because the ten are chosen before the priority filter runs. ## Pitfalls 1. **Too early.** `source.AsEnumerable().Where(...)` fetches everything and filters in memory; every operator after the switch loses the provider. 2. **Hidden switches.** A method parameter or variable typed `IEnumerable<T>` acts like an `AsEnumerable()` call the reader cannot see. 3. **`AsQueryable()` as a fix.** Calling it on an in-memory result does not send later operators back to the original provider; they run in `EnumerableQuery<T>`, still in memory.
- Why must IsPriority live in a class rather than be a local function for the queryable lambda to compile?The compiler does not allow a call to a local function inside an expression tree: CS8110, "An expression tree may not contain a reference to a local function". In a delegate lambda the same call is fine. Move the helper to a static class, or move the call after `AsEnumerable()`.
- When would you choose ToList() over AsEnumerable() before the in-memory step?When the in-memory part enumerates more than once, when you must close or release the source before continuing, or when you want execution to happen at a known point. `AsEnumerable()` keeps the query deferred and streaming, so each enumeration runs the provider's part again; `ToList()` runs it once and buffers the whole result.
- AsEnumerable() executes the query and copies the results into a list
- Putting AsEnumerable() first is harmless because the provider still optimises the rest
- The compiler rejects a queryable lambda that calls a method the provider cannot translate
- AsQueryable() turns an in-memory list into a query that runs at the data source
- After AsEnumerable(), a later Take or OrderBy is still sent to the provider