LINQ Interview Question #119

Why should you avoid unnecessary ToList calls in a LINQ pipeline?

LINQ Performance, EF Core LINQ, Expressions & Advanced Queries Senior Advanced

Quick Interview Answer

Every ToList materializes the current query and creates an in-memory list. Unnecessary materialization can allocate memory, break provider-side query composition, and cause later operations to run in the application rather than at the database.

Detailed Explanation

Every ToList materializes the current query and creates an in-memory list. Unnecessary materialization can allocate memory, break provider-side query composition, and cause later operations to run in the application rather than at the database.

Use ToList at a deliberate boundary where a concrete collection is actually required.

Code Example

// Keep composing before execution.
var result = await db.Products
    .Where(p => p.IsActive)
    .OrderBy(p => p.Name)
    .Take(50)
    .Select(p => new { p.Id, p.Name })
    .ToListAsync();