yield, deferred execution and IQueryable
A LINQ query like Where or Select does not run where you write it; it runs when someone enumerates it. This deferred execution is powered by yield and iterators, and the same idea behind IQueryable decides whether your filter runs in the app or in the database.
32.1 Why is it used?
- Lazy iterators produce values one at a time, so huge or endless data never has to sit in memory at once.
- Work stops early: if the consumer breaks out of foreach, the remaining values are never computed.
- IQueryable keeps a query as a tree so a provider (EF Core) can turn it into SQL and the database filters the rows.
- Not knowing when a query runs causes real bugs: filters running twice, later changes leaking into results, whole tables loaded into memory.
32.2 The bug: when did the query run?
- Where is written before orders.Add(3000), yet 3000 shows up in the result.
- checks is 8: the filter ran twice over 4 orders (once for Count, once for string.Join).
List<decimal> orders = [499, 1299, 2499];var checks = 0; var big = orders.Where(p =>{ checks++; return p > 1000;}); orders.Add(3000); Console.WriteLine(big.Count());Console.WriteLine(string.Join(", ", big));Console.WriteLine($"checks: {checks}");$ dotnet run Bug.cs31299, 2499, 3000checks: 8- Step 1
1.orders.Where(...) written: only a recipe, no data
- Step 2
2.orders.Add(3000) changes the source list
- Step 3
3.Count(): recipe run #1 over 4 items
- Step 4
4.string.Join: recipe run #2 over 4 items
- Step 5
5.checks = 8, and 3000 is in the result
Every enumeration runs the query again
32.3 yield return: one value at a time
- A method returning IEnumerable<T> with yield return is an iterator.
- yield return hands out one value and pauses the method right there.
- The next value is made only when foreach asks for it; after break, id 3 is never made.
- This is exactly the laziness Where and Select have.
foreach (var id in OrderIds()){ Console.WriteLine($"got {id}"); if (id == 2) break;} static IEnumerable<int> OrderIds(){ for (var id = 1; id <= 3; id++) { Console.WriteLine($"making {id}"); yield return id; }}$ dotnet run Yield.csmaking 1got 1making 2got 232.4 Inside foreach: IEnumerator
- IEnumerable<T> has only GetEnumerator(); IEnumerator<T> has MoveNext() and Current.
- foreach is just: GetEnumerator, then while (MoveNext()) use Current, then Dispose.
- The compiler turns a yield method into a generated state machine class (the odd type name in the output).
- yield break ends the sequence immediately, so OrderIds(false).Count() is 0.
var ids = OrderIds(open: true);Console.WriteLine(ids.GetType().Name); using var e = ids.GetEnumerator();while (e.MoveNext()) Console.WriteLine(e.Current); Console.WriteLine(OrderIds(false).Count()); static IEnumerable<int> OrderIds(bool open){ if (!open) yield break; yield return 101; yield return 102;}$ dotnet run Enumerator.cs<<<Main>$>g__OrderIds|0_0>d1011020- Step 1
1.foreach calls GetEnumerator: no method code has run yet
- Step 2
2.MoveNext runs the method up to the next yield return
- Step 3
3.Current returns that yielded value
- Step 4
4.Repeat MoveNext / Current for each item
- Step 5
5.Method ends or yield break: MoveNext returns false, loop stops
The compiler builds this state machine
32.5 Deferred vs immediate execution
| Kind | Operators | When it runs |
|---|---|---|
| Deferred (lazy) | Where, Select, OrderBy, GroupBy, Skip, Take | On every enumeration (foreach, ToList, Count...) |
| Immediate | ToList, ToArray, ToDictionary, Count, Sum, First, Max | Right now, once; the result is fixed |
- Fix for the bug: add ToList() so the query runs once and the result is stored.
- Now the count is 2, 3000 is not included, and checks is only 3.
List<decimal> orders = [499, 1299, 2499];var checks = 0; var big = orders.Where(p =>{ checks++; return p > 1000;}).ToList(); orders.Add(3000); Console.WriteLine(big.Count);Console.WriteLine(string.Join(", ", big));Console.WriteLine($"checks: {checks}");$ dotnet run Fix.cs21299, 2499checks: 332.6 Checkpoint
- Select is deferred and reads prices only when foreach runs.
- By then prices[0] is already 500, so the output is 1000 and 400, not 200 and 400.
var prices = new List<int> { 100, 200 };var doubled = prices.Select(p => p * 2); prices[0] = 500; foreach (var p in doubled) Console.WriteLine(p);$ dotnet run Checkpoint.cs100040032.7 IQueryable: the query is a tree
- IQueryable looks like IEnumerable and gives the same result here.
- But query.Expression prints a readable tree containing Where and p > 1000.
- The provider decides how to run that tree; with AsQueryable it is EnumerableQuery, which runs in memory.
- With EF Core the provider translates the tree to SQL (covered in the EF Core videos).
List<int> orders = [499, 1299, 2499]; IEnumerable<int> list = orders .Where(p => p > 1000);IQueryable<int> query = orders.AsQueryable() .Where(p => p > 1000); Console.WriteLine(string.Join(", ", list));Console.WriteLine(string.Join(", ", query));Console.WriteLine(query.Expression);var provider = query.Provider.GetType();Console.WriteLine(provider.Name);$ dotnet run Queryable.cs1299, 24991299, 2499System.Collections.Generic.List`1[System.Int32] .Where(p => (p > 1000))EnumerableQuery`132.8 Expression trees: code as data
- Func<int,bool> is compiled code: you can only call it.
- Expression<Func<int,bool>> makes the compiler build data describing the lambda; its Body is a BinaryExpression.
- You can read it: NodeType GreaterThan, Right 1000. Compile() turns it back into a runnable function.
- This is how providers like EF Core read your lambda and produce SQL.
using System.Linq.Expressions; Func<int, bool> isBig = p => p > 1000;Expression<Func<int, bool>> isBigExpr = p => p > 1000; Console.WriteLine(isBig(1299));Console.WriteLine(isBigExpr.Body); var body = (BinaryExpression)isBigExpr.Body;Console.WriteLine(body.NodeType);Console.WriteLine(body.Right); var compiled = isBigExpr.Compile();Console.WriteLine(compiled(1299));$ dotnet run Expr.csTrue(p > 1000)GreaterThan1000True32.9 Comparison: IEnumerable vs IQueryable
| Point | IEnumerable<T> | IQueryable<T> |
|---|---|---|
| Operators take | Func delegate (compiled code) | Expression tree (data) |
| Where the work happens | App memory | Provider, e.g. database via SQL |
| Typical source | List, array, yield iterator | EF Core DbSet |
| Execution | Deferred | Deferred |
| Data over the wire | All rows, then filter | Only matching rows |
- Step 1
1.IEnumerable: operators take a Func, filter runs in memory
- Step 2
2.IQueryable: operators take an Expression, query becomes a tree
- Step 3
3.Provider translates the tree (EF Core: SQL)
- Step 4
4.Database returns only matching rows
- Step 5
5.Both run only on foreach / ToList
IQueryable: work in the database; IEnumerable: work in the app
32.10 Common mistakes
- Enumerating a query twice: it runs twice and may see changed data; call ToList once if you need the result twice.
- Side effects (counters, logging, DB writes) inside a Where lambda: when and how often it runs is not fixed.
- Passing an IQueryable into a helper that takes IEnumerable: Enumerable.Where runs, and with a database the whole table comes into the app.
- Myth: AsQueryable makes a list fast like a database. It is only a wrapper that still runs in memory, even a bit slower.
static IEnumerable<Order> BigOrders( IEnumerable<Order> orders) => orders.Where(o => o.Total > 1000); // big is IQueryable<Order>: False// with a database: all rows come// to the app, filter runs in memorystatic IQueryable<Order> BigOrders( IQueryable<Order> orders) => orders.Where(o => o.Total > 1000); // big is IQueryable<Order>: True// big.Expression:// ...Where(o => (o.Total > 1000))32.11 Rules
- A query is a recipe: needed twice? ToList / ToArray first.
- Large or streaming data: write a lazy iterator with yield.
- Keep database queries as IQueryable and filter before ToList.
- No side effects inside LINQ lambdas.
32.12 Interview tips
- Deferred execution: Where/Select do not run until enumerated; ToList, Count, First run immediately.
- yield return makes the compiler generate an IEnumerator state machine; values are produced on MoveNext.
- IEnumerable works in memory with Func; IQueryable builds an expression tree that a provider like EF Core translates to SQL.
- Need the result twice? Call ToList so the query runs only once.
- Keep helper parameters and return types IQueryable so filters reach the database.