
Building Expression Trees
The System.Linq.Expressions namespace provides an API for building expression trees manually. The Expression class contains static factory methods that create expression tree nodes of specific types, for example a ParameterExpression, which represents a named parameter expression, or a MethodCallExpression, which represents a method call. ParameterExpression, MethodCallExpression, and the other expression-specific expression tree types are also defined in the System.Linq.Expressions namespace. These types derive from the abstract type Expression.
The compiler can also build an expression tree for you. A compiler-generated expression tree is always rooted in a node of type Expression<(Of <(TDelegate>)>); that is, its root node represents a lambda expression.
The following code example demonstrates two ways to create an expression tree that represents the lambda expression num => num < 5 (C#) or Function(num) num < 5 (Visual Basic).
' Import the following namespace to your project: System.Linq.Expressions
' Manually build the expression tree for the lambda expression num => num < 5.
Dim numParam As ParameterExpression = Expression.Parameter(GetType(Integer), "num")
Dim five As ConstantExpression = Expression.Constant(5, GetType(Integer))
Dim numLessThanFive As BinaryExpression = Expression.LessThan(numParam, five)
Dim lambda1 As Expression(Of Func(Of Integer, Boolean)) = _
Expression.Lambda(Of Func(Of Integer, Boolean))( _
numLessThanFive, _
New ParameterExpression() {numParam})
' Let the compiler generate the expression tree for
' the lambda expression num => num < 5.
Dim lambda2 As Expression(Of Func(Of Integer, Boolean)) = Function(ByVal num) num < 5
// Add the following using directive to your code file:
// using System.Linq.Expressions;
// Manually build the expression tree for
// the lambda expression num => num < 5.
ParameterExpression numParam = Expression.Parameter(typeof(int), "num");
ConstantExpression five = Expression.Constant(5, typeof(int));
BinaryExpression numLessThanFive = Expression.LessThan(numParam, five);
Expression<Func<int, bool>> lambda1 =
Expression.Lambda<Func<int, bool>>(
numLessThanFive,
new ParameterExpression[] { numParam });
// Let the compiler generate the expression tree for
// the lambda expression num => num < 5.
Expression<Func<int, bool>> lambda2 = num => num < 5;