如何合并Expression< Func< MyClass,bool>>> []?

如何合并Expression< Func< MyClass,bool>>> []?

问题描述:

我有一个

Expression<Func<MyClass,bool>>

但是,我想将它们全部加在一起以得到该类型的单个项目.我该怎么做呢?我可以强制转换Expression.And的结果吗?

However, I want to AND them all together to get just a single item of that type. How do I do this? Can I cast the result of Expression.And?

如果使用以下扩展方法:

If you use the following extension method:

public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
                                                       Expression<Func<T, bool>> expr2)
{
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
}

从此处: http://www.albahari.com/nutshell/predicatebuilder.aspx

然后,您只需编写此代码即可将它们全部折叠为一个表达式.

Then you can just write this to fold them all down to one expression.

public Expression<Func<T, bool>> AggregateAnd(Expression<Func<T,bool>>[] input)
{
    return input.Aggregate((l,r) => l.And(r));
}