1.5. Expression Trees

LINQ can treat lambda expressions as data at run time. The type Expression<T> represents an expression tree that can be evaluated and changed at run time. It is an in-memory hierarchical data representation where each tree node is part of the entire query expression. There will be nodes representing the conditions, the left and right part of the expression, and so on.

Expression trees make it possible to customize the way LINQ works when it builds queries. For example, a database provider not supported natively by LINQ could provide libraries to translate LINQ expression trees into database queries.

Listing 1-5 shows how to represent a lambda expression with an expression tree.

Example 1-5. Using an Expression Tree
Expression<Func<Person, bool>> e = p => p.ID == 1;
BinaryExpression    body  = (BinaryExpression)e.Body;
MemberExpression    left  = (MemberExpression)body.Left;
ConstantExpression  right = (ConstantExpression)body.Right;

Console.WriteLine(left.ToString());
Console.WriteLine(body.NodeType.ToString());
Console.WriteLine(right.Value.ToString());

First you define an Expression<T> variable, e, and assign it the lambda expression you want to evaluate. Then you obtain the "body" of the expression from the Body property of the Expression<T> object. Its Left and Right properties contain the left and right operands of the expression. Depending on the expression, those properties will assume the related type expressed in the formula. In a more complex case you don't know the type to convert to, so you have to use a switch expression to implement any possible case. In our example, to the left there is a member of the List<Person> type while to the right there is a constant. You cast those properties to the appropriate types.

Figure 1-3 shows the result of running the snippet in Listing 1-5.

Figure 1-3. Displaying a node of an expression tree

The result is clear; the Left property provides the left part of the expression, p.ID. The Right property provides the right part of the expression, 1. Finally, the Body property provides a symbol describing the condition of the expression. In this case EQ stands for equals.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.238.134