LINQ Interview Question #99

What is the effect of placing Where before or after Select?

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

Quick Interview Answer

The result depends on what data the predicate requires and what shape Select produces. Filtering before projection is often natural when the predicate uses source properties. Filtering after projection is valid when the projected shape contains everything required.

Detailed Explanation

The result depends on what data the predicate requires and what shape Select produces. Filtering before projection is often natural when the predicate uses source properties. Filtering after projection is valid when the projected shape contains everything required.

For IQueryable providers, both patterns may translate efficiently when supported, but developers should inspect generated queries for performance-sensitive code.

Code Example

var result = products
    .Where(p => p.IsActive)
    .Select(p => new
    {
        p.Id,
        p.Name,
        p.Price
    })
    .Where(p => p.Price > 100);