Linq Expression Tree
Linq Expression : Switching between data Structure and code
/////////////////////////////////////////////
/// Linq Expression Tree for (x,y ) => x * y;
/// Directly build the lambda expression ///
/////////////////////////////////////////////
Expression lambdaExpression1 = (x, y) => x * y;
Func lamba1Delegate = lambdaExpression1.Compile();
int resultLamda1 = lamba1Delegate(100, 100);
Console.WriteLine(resultLamda1.ToString());
/////////////////////////////////////////////
Or you can do the following
Expression Func int int int AddOperation = (x, y) => x + y;
int result = AddOperation.Compile()(10, 10);
/////////////////////////////////////////////
///// Rebuilding and Executing Linq Expression
//// Manually
/////////////////////////////////////////////
ParameterExpression p1 = Expression.Parameter(typeof(int), "x");
ParameterExpression p2 = Expression.Parameter(typeof(int), "y");
BinaryExpression operation = Expression.Multiply(p1, p2);
Expression> lambdaExpression2 = Expression.Lambda>(operation, new ParameterExpression[] { p1 , p2});
Func FunctionForLambda2 = lambdaExpression2.Compile();
int resultLamda2 = FunctionForLambda2(12, 12);
Console.WriteLine(resultLamda2.ToString());
Sample Linq Expression
Another example to add x + y + z
/// x + y + z
ParameterExpression varx= Expression.Parameter(typeof(int), "x");
ParameterExpression vary = Expression.Parameter(typeof(int), "y");
ParameterExpression varz = Expression.Parameter(typeof(int), "z");
/// x + y
Expression operationAdd = Expression.Add(varx, vary);
// (x+y) + z
Expression operationAdd2 = Expression.Add(operationAdd, varz);
LambdaExpression expr1 = Expression.Lambda(operationAdd2, varx, vary, varz);
/// Since we're passing in 3 parameters .....
Func FuncCall2 = (Func)expr1.Compile();
int result4 = FuncCall2(10, 10, 10);
Comments