连接lambda表达式

时间:2018-03-09 17:13:21

标签: c# linq lambda expression-trees

我尝试连接动态生成的2个lambda表达式:

public Expression<Func<User, bool>> Expres(int id)
{
    var argument = Expression.Parameter(typeof(User));
    var left = Expression.Property(argument,"id");
    var right = Expression.Constant(id);
    BinaryExpression binary = Expression.Equal(left, right);
    Expression<Func<User, bool>> exp = Expression.Lambda<Func<User, bool>>(
        binary,
        new[] { argument }
    );

    return exp;
}

示例:

>Expres(255);
Param_0.id == 255

>Expres(10);
Param_0.id == 10

但是,当合并它们时......

>expression = Expression.And(exp1, exp2);
  

(Param_0.Id == 255)和(Param_1.Id == 10)

>Expression.Lambda<Func<TEntidad, bool>>(expression, new[] { argument });
  

Param_0 =&gt; ((Param_1.Id == 255)和(Param_2.Id == 10)

但它会产生比所需更多的依赖关系,以及我所期望的结果:

  

Param_0 =&gt; ((Param_0.Id == 255)和(Param_0.Id == 10)

0 个答案:

没有答案