Search code examples
dynamiclambdatreeexpressionexpression-trees

Building dynamic lambda expressions


I know how to build a simple lambda like x => x > 5:

int[] nbs = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };            
IEnumerable<int> result1 = nbs.Where(x => x > 5);

ParameterExpression parameter = Expression.Parameter(typeof(int), "x");
ConstantExpression constant = Expression.Constant(5);
BinaryExpression expressionBody = Expression.GreaterThan(parameter, constant);
Expression<Func<int, bool>> expression = Expression.Lambda<Func<int, bool>>(expressionBody, parameter);
IEnumerable<int> result2 = nbs.Where(expression.Compile());

But how do I build a lambda like x => whiteNbs.Contains(x) in a similar way as above:

int[] nbs = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> whiteNbs = new List<int>() { 1, 5 };            
IEnumerable<int> result = nbs.Where(x => whiteNbs.Contains(x));

Solution

  • Replace binary GreaterThan expression with a MethodCallExpression.

    int[] nbs = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    
    var elementType = typeof(int);
    var x = Expression.Parameter(elementType, "x");
    var whiteNbs = Expression.Constant(new List<int>() {1, 5});
    
    var contains = Expression.Call(typeof(Enumerable),
        "Contains",
        new[] {elementType},
        whiteNbs, 
        x
      );
    
    var lambda = Expression.Lambda<Func<int, bool>>(contains, x);
    var result = nbs.Where(lambda.Compile());