How to combine (OR) two expression trees

2019-03-01 03:52发布

问题:

I have two expression trees of type : Expression<Func<string, bool>> and I would like to obtain a single Expression that will do the OR of the two expressions (passing the same string parameter to both expressions) Any idea?

回答1:

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


回答2:

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