LINQ Interview Question #95
How can LINQ queries be built dynamically?
Deferred Execution, Immediate Execution & Query Behavior Mid-Level Intermediate
Quick Interview Answer
Start with an IEnumerable<T> or IQueryable<T> variable and conditionally append operators. For more complex provider-based scenarios, expression trees can be constructed or combined to create dynamic predicates.
Detailed Explanation
Start with an IEnumerable<T> or IQueryable<T> variable and conditionally append operators. For more complex provider-based scenarios, expression trees can be constructed or combined to create dynamic predicates.
The important point is to preserve IQueryable while building database-side conditions if translation by the provider is desired.
Code Example
IQueryable<Product> query = db.Products;
if (!string.IsNullOrWhiteSpace(search))
query = query.Where(
p => p.Name.Contains(search));
if (categoryId.HasValue)
query = query.Where(
p => p.CategoryId == categoryId);
return await query.ToListAsync();