有没有办法使用||或者&&表达式之间的运算

时间:2013-06-13 11:13:20

标签: c# expression

我正在尝试重构一个复杂的Linq查询。 我想知道是否有办法可以做到这样的事情: 假设我们有两个表达式:

Expression<Func<object,bool>> exp1=....;
Expression<Func<object,bool>> exp2=....;

Expression<Func<object,bool>> exp3=exp1 || exp2;

2 个答案:

答案 0 :(得分:2)

基本上你需要重写其中一棵树,以便你可以组合表达式。幸运的是ExpressionVisitor帮助我们:

static void Main()
{
    Expression<Func<object, bool>> exp1 = x => ((string)x).StartsWith("a");
    Expression<Func<object, bool>> exp2 = y => ((string)y).StartsWith("b");
    // the two expressions here are purely for illustration

    var exp3 = Combine(exp1, exp2, Expression.OrElse); // i.e. ||
    var exp4 = Combine(exp1, exp2, Expression.AndAlso); // i.e. &&
}
static Expression<Func<TValue, TResult>> Combine<TValue, TResult>(
    Expression<Func<TValue, TResult>> left,
    Expression<Func<TValue, TResult>> right,
    Func<Expression, Expression, BinaryExpression> combination)
{
    // rewrite the body of "right" using "left"'s parameter in place
    // of the original "right"'s parameter
    var newRight = new SwapVisitor(right.Parameters[0], left.Parameters[0])
                        .Visit(right.Body);
    // combine via && / || etc and create a new lambda
    return Expression.Lambda<Func<TValue, TResult>>(
        combination(left.Body, newRight), left.Parameters);
}
class SwapVisitor : ExpressionVisitor {
    private readonly Expression from, to;
    public SwapVisitor(Expression from, Expression to) {
        this.from = from;
        this.to = to;
    }
    public override Expression Visit(Expression node) {
        return node == from ? to : base.Visit(node);
    }
}

请注意,这也允许其他任意用途,例如:

Expression<Func<object, int>> exp1 = x => x.GetHashCode();
Expression<Func<object, int>> exp2 = y => y.ToString().Length;

var exp3 = Combine(exp1, exp2, Expression.Add);
// which is: x => x.GetHashCode() + x.ToString().Length;

我认为没有实用用于......但它确实存在; p

答案 1 :(得分:1)

您可以使用Dynamic Linq QueryPredicateBuilder