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

5

我有一个数组

Expression<Func<MyClass,bool>>

然而,我想将它们全部AND在一起,以便只得到该类型的单个项目。我该怎么做?我可以强制转换Expression.And的结果吗?

1
我以前使用过PredicateBuilder来完成这个任务--http://www.albahari.com/nutshell/predicatebuilder.aspx - John Kalberer
你希望最终结果也是 Expression<Func<MyClass,bool>> 吗? - yamen
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));
}

最终发现上述代码实际上对大多数情况都不起作用,因为Invoke无法转换为SQL。我在这里找到了类似但更兼容的代码:https://dev59.com/P3VD5IYBdhLWcg3wDG_l - Brannon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接