如何组合Expression <func <myclass,bool>&gt; []?</func <myclass,bool>

时间:2012-04-30 21:24:02

标签: c# linq expression-trees

我有一个

数组
Expression<Func<MyClass,bool>>

但是,我想将它们全部组合在一起以获得该类型的单个项目。我该怎么做呢?我可以投射Expression.And的结果吗?

1 个答案:

答案 0 :(得分:5)

如果您使用以下扩展方法:

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

然后你可以写这个将它们全部折叠成一个表达式。

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