简体   繁体   中英

How to combine (OR) two expression trees

我有两种类型的表达式树: Expression<Func<string, bool>> ,我想获得一个单独的Expression,它将对两个表达式进行或运算(将相同的字符串参数传递给两个表达式)。

You can use PredicateBuilder from LINQKit to do this. For example:

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

You can try combining them in a Expression.Lambda expression and then using Expression.Or to check if one of them is true.

Here is an example:

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);

Maybe you can get more info here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM