Expression trees
Context: Expression trees represent lambda expressions as data structures (abstract syntax trees). They are used to analyze, modify, or translate lambdas (e.g., to SQL).
using System.Linq.Expressions;
Expression<Func<int, int>> expr = x => x * 2;Console.WriteLine(expr); // x => (x * 2)
// Compile and invokeFunc<int, int> compiled = expr.Compile();Console.WriteLine(compiled(5)); // 10Inspecting expression trees
Section titled “Inspecting expression trees”var body = expr.Body as BinaryExpression;Console.WriteLine(body.NodeType); // MultiplyBuilding expressions manually
Section titled “Building expressions manually”ParameterExpression param = Expression.Parameter(typeof(int), "x");ConstantExpression constant = Expression.Constant(2);BinaryExpression multiply = Expression.Multiply(param, constant);Expression<Func<int, int>> expr2 = Expression.Lambda<Func<int, int>>(multiply, param);Real-world usage example
Section titled “Real-world usage example”ORM query translation: Entity Framework Core converts LINQ queries (expression trees) to SQL.
Example: EF Core Querying uses expression trees to translate Where(x => x.Id == 1) into WHERE [Id] = 1.