System.Linq.Expressions 名前空間は、式ツリーを手作業で作成するための API を提供します。Expression クラスには、名前付きのパラメータ式を表す ParameterExpression や、メソッド呼び出しを表す MethodCallExpression など、特定の型のツリー ノードを作成する静的ファクトリ メソッドが含まれています。ParameterExpression や MethodCallExpression などの式固有の式ツリー型も、System.Linq.Expressions 名前空間で定義されます。これらの型は Expression 抽象型から派生したものです。
コンパイラにより、自動的に式を作成することもできます。コンパイラにより生成された式ツリーは、常に Expression<(Of <(TDelegate>)>) 型のノードをルートとします。つまり、この式ツリーのルート ノードはラムダ式を表します。
次のコード例では、ラムダ式 num => num < 5 (C#) または Function(num) num < 5 (Visual Basic) を表す式ツリーを 2 つの方法で作成します。
' 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;