Expressions

From no name for this wiki
Jump to: navigation, search

Simple Expressions

System.Linq.Expressions.Expression<Func<int, int, bool>> largeSumTest =
    (num1, num2) => (num1 + num2) > 1000;
 
// Create an InvocationExpression that represents applying 
// the arguments '539' and '281' to the lambda expression 'largeSumTest'.
System.Linq.Expressions.InvocationExpression invocationExpression =
    System.Linq.Expressions.Expression.Invoke(
        largeSumTest,
        System.Linq.Expressions.Expression.Constant(539),
        System.Linq.Expressions.Expression.Constant(281));
 
Console.WriteLine(invocationExpression.ToString());

As Expressions

 /*
System.Linq.Expressions.Expression<Func<int, int, bool>> largeSumTest =
    (num1, num2) => (num1 + num2) > 1000;
    */
 
//num1
ParameterExpression param1 = Expression.Parameter(typeof(int), "num1");
//num2
ParameterExpression param2 = Expression.Parameter(typeof(int), "num2");
//num1 + num2
BinaryExpression add = Expression.Add(param1, param2);
 
//1000
ConstantExpression constant = Expression.Constant(1000, typeof(int));
 
//(num1 + num2) > 1000
BinaryExpression greaterThan = Expression.GreaterThan(add, constant);
 
//(num1, num2) => (num1 + num2) > 1000;
Expression<Func<int, int, bool>> largeSumTest = Expression.Lambda<Func<int, int, bool>>(greaterThan, param1, param2);
 
var t = largeSumTest.Compile();
bool x = t(23, 45);
 
ConstantExpression param1Value = Expression.Constant(50, typeof(int));
ConstantExpression param2Value = Expression.Constant(960, typeof(int));
 
InvocationExpression invocationExpression = Expression.Invoke(largeSumTest, param1Value, param2Value);

Predicate Builder

public static class PredicateBuilder
    {
        public static Expression<Func<T, bool>> True<T> () { return f => true; }
        public static Expression<Func<T, bool>> False<T> () { return f => false; }
 
        public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
                                                  Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
 
            return Expression.Lambda<Func<T, bool>>
                 (Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
        }
 
        public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
                                                   Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
            return Expression.Lambda<Func<T, bool>>
                 (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
        }
    }