Building dynamic lambda expressions

dynamic expression expression-trees lambda tree

Question

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));
1
0
9/17/2018 5:55:32 AM

Accepted Answer

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());
0
9/17/2018 8:08:04 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow