How to combine (OR) two expression trees

2019-03-01 04:15发布

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?

2条回答
Deceive 欺骗
2楼-- · 2019-03-01 04:28

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();
查看更多
劫难
3楼-- · 2019-03-01 04:39

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

查看更多
登录 后发表回答