How to combine (OR) two expression trees

左心房为你撑大大i 提交于 2020-02-25 21:49:55

问题


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



来源:https://stackoverflow.com/questions/17597201/how-to-combine-or-two-expression-trees

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!