如何组合(OR)两个表达式树

时间:2013-07-11 15:14:14

标签: c# expression-trees

我有两个类型为Expression<Func<string, bool>>的表达式树,我想获得一个表达式,它将执行两个表达式的OR(将相同的字符串参数传递给两个表达式) 有什么想法吗?

2 个答案:

答案 0 :(得分:4)

您可以使用PredicateBuilder from LINQKit执行此操作。例如:

Expression<Func<string, bool>> e1 = …;
Expression<Func<string, bool>> e2 = …;
Expression<Func<string, bool>> combined = e1.Or(e2).Expand();

答案 1 :(得分:1)

您可以尝试在Expression.Lambda表达式中合并它们,然后使用Expression.Or检查其中一个是否为真。

以下是一个例子:

Expression<Func<Car, bool>> theCarIsRed = c1 => c1.Color == "Red";
Expression<Func<Car, bool>> theCarIsCheap = c2 => c2.Price < 10.0;
Expression<Func<Car, bool>> theCarIsRedOrCheap = Expression.Lambda<Func<Car, bool>>(
    Expression.Or(theCarIsRed.Body, theCarIsCheap.Body), theCarIsRed.Parameters.Single());
var query = carQuery.Where(theCarIsRedOrCheap);

也许您可以获得更多信息here