LINQ Interview Question #25
Why is it important to know whether a LINQ query is executed in memory or by a database provider?
LINQ Fundamentals, Syntax, IEnumerable & IQueryable Junior Beginner
Quick Interview Answer
The execution location affects performance, supported operations, memory usage, network traffic, and even query semantics. An IEnumerable<T> query normally runs in application code, while an IQueryable<T> query may be translated and executed by a remote provider such as a database.
Detailed Explanation
The execution location affects performance, supported operations, memory usage, network traffic, and even query semantics. An IEnumerable<T> query normally runs in application code, while an IQueryable<T> query may be translated and executed by a remote provider such as a database.
For database work, filtering, projection, ordering, and pagination should usually remain provider-translatable until the necessary data has been retrieved. Materializing too early can cause unnecessary rows and columns to be loaded into memory.
Code Example
// Better: filter before materialization.
var products = await db.Products
.Where(p => p.IsActive && p.Price > 100)
.Select(p => new { p.Id, p.Name })
.ToListAsync();
// Avoid loading the whole table before filtering
// unless in-memory processing is intentional.