|
|
От: |
GlebZ
|
|
| Дата: | 15.09.05 12:29 | ||
| Оценка: | |||
Exercise 4 – Using Lambda Expressions to Create Expression Trees
In addition to treating data as objects, LINQ provides the ability to treat expressions as data at runtime. LINQ defines a new type, Expression<T>, that represents an expression tree, an in-memory representation of a lambda expression. Expression trees allow developers to treat lambda expressions as data, allowing for inspection and modification of lambda expressions in code. This feature will be used to enable an ecosystem of third-party libraries that leverage the base query abstractions that are part of LINQ. For example, a database access implementation might leverage this facility to translate expression trees into suitable query statements for a particular kind of database.
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,
mult.NodeType, en.Name, three.Value, five.Value);
}