skip to content

In C#, how do you build an Expression<Func<Order, bool>> filter at run time with the Expression factory methods, and why does joining two lambdas' bodies fail at Compile()?

level: seniorimportance: should knowfreq 40%

answer

  1. build from the leaves up
  2. Parameter, Property, Constant, Lambda
  3. parameters are matched by object
  4. rebind with an ExpressionVisitor

basics

~20 s

Create one ParameterExpression, build nodes with Expression.Property, Constant, GreaterThan and AndAlso, then wrap them with Expression.Lambda<Func<Order, bool>>. Joining two compiler-made lambdas' bodies fails because each refers to its own parameter object, so one is unbound.

solid answer

~30 s

Expression trees are immutable, so you build from the leaves up: `var o = Expression.Parameter(typeof(Order), "o")`, then `Expression.Property(o, nameof(Order.Total))`, `Expression.Constant(100m)`, `Expression.GreaterThan(...)`, combine conditions with `Expression.AndAlso`, and finish with `Expression.Lambda<Func<Order, bool>>(body, o)`. The result can go to `Queryable.Where`, or `Compile()` into a delegate. The classic bug is combining `x => x.Total > 100m` and `y => y.Status == "Open"` with `Expression.AndAlso(a.Body, b.Body)` and `a.Parameters`: parameters are matched by object identity, not by name, so `y` is referenced but not declared and `Compile()` throws `InvalidOperationException` naming it. Fix it with an `ExpressionVisitor` that replaces one parameter with the other.

code

csharp · 15 lines
csharp
using System.Linq.Expressions;

// o => o.Total > 100m && o.Status == "Open", built from factory methods
ParameterExpression o = Expression.Parameter(typeof(Order), "o");
Expression totalTest = Expression.GreaterThan(
    Expression.Property(o, nameof(Order.Total)), Expression.Constant(100m));
Expression statusTest = Expression.Equal(
    Expression.Property(o, nameof(Order.Status)), Expression.Constant("Open"));
var filter = Expression.Lambda<Func<Order, bool>>(Expression.AndAlso(totalTest, statusTest), o);

Console.WriteLine(filter);   // o => ((o.Total > 100) AndAlso (o.Status == "Open"))
Func<Order, bool> compiled = filter.Compile();
Console.WriteLine(compiled(new Order(3, 900m, "Open")));   // True

record Order(int Id, decimal Total, string Status);

go deeper

for a junior

Recall that the Expression class has factory methods such as Parameter, Property, Constant and Lambda, and that a built tree is compiled with Compile() before it runs in memory.

for a middle

Explain building from the leaves up, why trees are immutable, and which mistakes surface only at run time, such as a wrong member name or mismatched operand types.

for a senior

Diagnose the unbound-parameter failure when filters are combined, and fix it with a parameter-replacing ExpressionVisitor rather than an Invoke node a provider may not translate.

for a principal

Judge when hand-built trees are worth their run-time-only errors and review cost, compared with a fixed set of filter methods the compiler can check.

## When you build a tree by hand The compiler builds expression trees for lambdas you write, but some filters are only known at run time: a search form with optional fields, a column chosen by name, rules loaded from configuration. For those you build the tree yourself with the static factory methods on `System.Linq.Expressions.Expression`, and pass the result to `Queryable.Where` (so a provider can translate it) or `Compile()` it into a delegate. Expression trees are **immutable**. Each factory method takes its children as arguments, so you build from the leaves up to the root. ## The building blocks | Factory method | Node it creates | Example | |---|---|---| | `Expression.Parameter(typeof(Order), "o")` | `ParameterExpression` | the lambda's `o` | | `Expression.Property(o, nameof(Order.Total))` | `MemberExpression` | `o.Total` | | `Expression.Constant(100m)` | `ConstantExpression` | `100` | | `Expression.GreaterThan(left, right)` | `BinaryExpression` | `o.Total > 100` | | `Expression.AndAlso(left, right)` | `BinaryExpression` | `a && b` | | `Expression.Lambda<Func<Order, bool>>(body, o)` | `Expression<Func<Order, bool>>` | `o => ...` | A typical dynamic filter: 1. Create **one** `ParameterExpression` for the element. 2. For each active criterion, build a comparison against a property of that parameter. 3. Fold the comparisons together with `Expression.AndAlso` (or `OrElse`). 4. Wrap the body with `Expression.Lambda<Func<Order, bool>>(body, parameter)`. 5. Use it with `Queryable.Where`, or call `Compile()` once and keep the delegate. Errors here are run-time errors, not compile errors: - `Expression.Property(o, "Totl")` throws `ArgumentException` because the member does not exist; `nameof` keeps the names checked by the compiler. - `Expression.GreaterThan` with a `decimal` property and an `int` constant throws `InvalidOperationException`, because no `>` operator is defined between the two types; build the constant with the property's type or add `Expression.Convert`. ## Optional criteria A search form usually yields a list of conditions, some of them absent. A robust builder: - starts from no body and adds one comparison per supplied field, each built against the **same** parameter; - returns the source unfiltered when no field is supplied, instead of building an empty lambda; if a lambda is required, `Expression.Constant(true)` is a valid body; - takes column names from a fixed allow-list and maps them with `nameof`, so user input never reaches `Expression.Property` as an arbitrary member name. ## Why joining two lambdas fails A common shortcut is to take two compiler-written filters and glue their bodies together: ```csharp Expression<Func<Order, bool>> big = x => x.Total > 100m; Expression<Func<Order, bool>> open = y => y.Status == "Open"; var broken = Expression.Lambda<Func<Order, bool>>( Expression.AndAlso(big.Body, open.Body), big.Parameters); ``` It builds, but `broken.Compile()` throws `InvalidOperationException` whose message names the variable `y`. The reasons: - Each lambda the compiler builds has its **own** `ParameterExpression` object. Naming both `o` would not help. - Nodes refer to parameters **by object identity**. `open.Body` still points at `y`, and the new lambda declares only `x`, so `y` is unbound. - A query provider that processes the tree typically fails on the same unbound parameter, so the problem is not limited to `Compile()`. ## Fixing it - **Rebind the parameter.** Write a small `ExpressionVisitor` that overrides `VisitParameter` and returns `x` wherever it meets `y`, then combine `big.Body` with the rewritten body. Because trees are immutable, the visitor returns a new tree and leaves `open` intact. - **Invoke the other lambda.** `Expression.Invoke(open, big.Parameters[0])` also produces a valid tree, but the result contains an `InvocationExpression`, and not every query provider can translate one; rebinding produces the same shape the compiler would have built for a single lambda. - **Build from one parameter in the first place** when you control the code that creates the criteria. ## Compiling and caching `Expression<TDelegate>.Compile()` returns a `TDelegate`, here `Func<Order, bool>`. It generates code, or falls back to an interpreter where dynamic code is not supported, so it costs far more than a call: compile once per distinct tree and reuse the delegate. `Compile(preferInterpretation: true)` requests the interpreter when compile cost matters more than call speed.

  • Why not just name both lambda parameters o so the bodies line up?
    Names are labels for printing. Each lambda the compiler converts gets its own `ParameterExpression` object, and nodes refer to that object, so two parameters called `o` are still two parameters. Only rewriting the body, or building every condition from one shared `ParameterExpression`, makes them the same.
  • Does Compile() always generate IL?
    No. Where dynamic code is not supported, as under Native AOT, `Compile()` returns a delegate backed by the expression interpreter, which is much slower per call. `Compile(preferInterpretation: true)` asks for the interpreter on purpose. Either way, compile a tree once and cache the delegate rather than compiling per call.

  • Two lambda parameters with the same name are the same parameter in a combined tree
  • Expression.Property with a misspelt name is caught by the compiler
  • You can add a condition by modifying the Body of an existing expression tree
  • Expression.AndAlso on two lambdas' bodies is all it takes to combine filters
  • Expression.Invoke is translated by every query provider, so rebinding is unnecessary