【问题标题】:Building dynamic lambda expressions构建动态 lambda 表达式
【发布时间】:2018-09-14 11:54:13
【问题描述】:

我知道如何构建一个简单的 lambda,例如 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());

但是如何以与上述类似的方式构建像 x => whiteNbs.Contains(x) 这样的 lambda:

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));

【问题讨论】:

    标签: dynamic lambda tree expression expression-trees


    【解决方案1】:

    将二进制GreaterThan 表达式替换为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());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      相关资源
      最近更新 更多