wasAsked.

What is deferred execution in LINQ and when does a LINQ query actually run?

Frequently Asked (All Companies) · Role not specified · technical

Published

Year not specified · C#, .NET

Community answers

Posted by wasAsked editorial collection

Deferred execution means a LINQ query is not executed when you define it. It runs only when you enumerate the results — for example with foreach, ToList(), ToArray(), Count(), First() or Sum(). Until then, the query is just a description of what to do. Example var numbers = new List<int> { 1, 2, 3 }; var evens = numbers.Where(n => n % 2 == 0); // nothing executed yet numbers.Add(4); foreach (var n in evens) Console.WriteLine(n); // prints 2 and 4 — the query runs now, seeing the added item The Where call returned an iterator object. The filtering logic ran only during the foreach, so it included the number added afterwards. Deferred vs immediate operators - Deferred (lazy): Where, Select, SelectMany, OrderBy, ThenBy, GroupBy, Join, Skip, Take, Distinct, Concat. They return IEnumerable<T> or IQueryable<T>. - Immediate: ToList, ToArray, ToDictionary, ToHashSet, Count, Sum, Average, Min, Max, First, Single, Any, All, Contains, Aggregate. They force execution and return a concrete result. Streaming vs buffering - Where and Select stream: they process one element at a time. - OrderBy, GroupBy and Reverse buffer: when enumeration starts, they read the entire source before returning the first result. When does a LINQ to Entities (EF Core) query run? - Building an IQueryable creates an expression tree; no SQL is sent. - SQL is generated and executed when you enumerate: ToListAsync(), FirstOrDefaultAsync(), CountAsync(), AnyAsync(), or a foreach (await foreach for async streams). IQueryable<Order> query = db.Orders.Where(o => o.Status == "Paid"); // no SQL yet if (customerId is not null) query = query.Where(o => o.CustomerId == customerId); // still no SQL var orders = await query.OrderBy(o => o.CreatedAt).Take(20).ToListAsync(ct); // SQL executes here This lets you compose queries conditionally and still send one efficient SQL statement. Benefits - Composability: build queries step by step. - Efficiency: work is done only if and when results are needed, and short-circuiting operators (First, Any, Take) stop early. - Works with infinite or very large sequences generated with yield return. Pitfalls interviewers like to hear 1. Multiple enumeration: enumerating the same deferred query twice executes it twice. With EF Core that means two database round trips; with an expensive generator, double work. var q = db.Orders.Where(...); var count = q.Count(); // query 1 var list = q.ToList(); // query 2 Fix: materialise once with ToList() when you need the results several times. 2. Captured variables: the query uses the variable's value at execution time, not at definition time. 3. Disposed resources: enumerating an EF Core query after the DbContext is disposed throws an exception. 4. Exceptions appear late: an error inside a Select lambda is thrown during enumeration, not where the query was defined, which can confuse debugging. 5. Side effects inside lambdas run each time the query is enumerated. Interview summary: "LINQ queries are lazy; they execute when enumerated by foreach or an immediate operator like ToList or Count. For EF Core, the SQL runs at that point. Materialise results once when you need them multiple times."

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics