LINQ Interview Question #100

What are good practices for controlling LINQ query execution?

Deferred Execution, Immediate Execution & Query Behavior Mid-Level Intermediate

Quick Interview Answer

Know whether the source is IEnumerable<T> or IQueryable<T>, understand which operators are deferred, and materialize only when a concrete snapshot is needed. Avoid accidental multiple enumeration of expensive sources.

Detailed Explanation

Know whether the source is IEnumerable<T> or IQueryable<T>, understand which operators are deferred, and materialize only when a concrete snapshot is needed. Avoid accidental multiple enumeration of expensive sources.

For database queries, keep translatable filtering, projection, ordering, and pagination server-side until execution. Use AsEnumerable only when intentionally switching to client-side processing, and use ToList or another materializer at a deliberate execution boundary.

Code Example

IQueryable<Product> query = db.Products
    .Where(p => p.IsActive)
    .OrderBy(p => p.Name)
    .Select(p => new Product
    {
        Id = p.Id,
        Name = p.Name
    });

var result = await query
    .Take(100)
    .ToListAsync();