5

我有一个数组

Expression<Func<MyClass,bool>>

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

4

1 回答 1

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));
}
于 2012-04-30T22:10:20.187 回答