Task 1 – Creating an Expression Tree using a Lambda Expression
In this task, you declare an expression tree and print a representation of the expression body.
1. Add the following using directive to gain access to the types in System.Expressions (at the top of the file): using System.Linq.Expressions;
2. Replace the code in the body of the Main method with the following code: static void Main(string[] args) { Expression<Func<int, bool>> filter = n => (n * 3) < 5;
BinaryExpression lt = (BinaryExpression) filter.Body; BinaryExpression mult = (BinaryExpression) lt.Left; ParameterExpression en = (ParameterExpression) mult.Left; ConstantExpression three = (ConstantExpression) mult.Right; ConstantExpression five = (ConstantExpression) lt.Right;
Console.WriteLine("({0} ({1} {2} {3}) {4})", lt.NodeType, }
This code creates an expression tree representation from the lambda expression. It then initializes local variables for each node of the tree. Finally, it outputs a LISP-style representation of the expression, to demonstrate a translation of the lambda expression to the expression tree. 3. Press Ctrl+F5 to run the code and see the following output in the console window: (LessThan (Multiply n 3) 5)
4. Press any key to terminate the application.
|