Roadmap › LINQ — Language Integrated Query › Module: LINQ Internals and EF Core
Lessons in this course (12)

10. Expression trees and dynamic queries

AdvancedMediumLesson 10 of 12

An expression tree is code as data: a tree of Expression nodes that a provider can inspect and translate.

csharp
Func<int, bool> del = n => n > 5;                      // compiled code
Expression<Func<int, bool>> expr = n => n > 5;         // data structure
Console.WriteLine(expr.Body);                          // (n > 5)
var compiled = expr.Compile();                         // can still compile and run

// Build a filter dynamically: p => p.Price > minPrice
var param = Expression.Parameter(typeof(Product), "p");
var body = Expression.GreaterThan(Expression.Property(param, nameof(Product.Price)), Expression.Constant(5000m));
var lambda = Expression.Lambda<Func<Product, bool>>(body, param);
var results = db.Products.Where(lambda);

// Simpler: compose conditionally
IQueryable<Product> query = db.Products;
if (category is not null) query = query.Where(p => p.Category == category);
if (minPrice is not null) query = query.Where(p => p.Price >= minPrice);

Libraries: System.Linq.Dynamic.Core (string-based dynamic LINQ), LinqKit (PredicateBuilder for OR conditions).