【问题标题】:how do I combine Expression<Func<MyClass,bool>>[]?如何组合 Expression<Func<MyClass,bool>>[]?
【发布时间】:2012-04-30 21:24:01
【问题描述】:

我有一个数组

Expression<Func<MyClass,bool>>

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

【问题讨论】:

标签: c# linq expression-trees


【解决方案1】:

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

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。我最终在这里找到了类似但更兼容的代码:stackoverflow.com/questions/110314/…
猜你喜欢
  • 2011-07-02
  • 2010-10-25
  • 1970-01-01
  • 2013-03-09
  • 2019-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-17
相关资源
最近更新 更多