LINQ Interview Question #116

What is dynamic LINQ predicate composition?

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

Quick Interview Answer

Dynamic predicate composition builds a final filter from conditions known only at runtime. A common approach is to start with IQueryable<T> and append Where clauses conditionally.

Detailed Explanation

Dynamic predicate composition builds a final filter from conditions known only at runtime. A common approach is to start with IQueryable<T> and append Where clauses conditionally.

For more advanced cases, expression trees can be combined programmatically. The resulting expression must remain translatable if it is intended for database execution.

Code Example

IQueryable<Product> query = db.Products;

if (categoryId.HasValue)
    query = query.Where(
        p => p.CategoryId == categoryId);

if (minPrice.HasValue)
    query = query.Where(
        p => p.Price >= minPrice.Value);