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?
Asked
Active
Viewed 2,401 times
2

Daniel Hilgarth
- 171,043
- 40
- 335
- 443

Dave
- 1,835
- 4
- 26
- 44
-
I'm not sure what your asking here, perhaps you can explain why your asking? – Bostwick Jul 11 '13 at 15:20
2 Answers
8
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();

svick
- 236,525
- 50
- 385
- 514
-
It works, but as I am going to use it with EF in a LinqToEntities query I can not use Invoke there. – Dave Jul 12 '13 at 22:59
-
@Dave That's what the `Expand()` is there for, it takes care of the `Invoke`. – svick Jul 13 '13 at 09:14
0
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

mathifonseca
- 1,465
- 1
- 15
- 17
-
1That doesn't work, because the parameter used in the body of `theCarIsCheap` no longer exists in the resulting expression. You need to use the long way with the ExpressionVisitor. – Daniel Hilgarth Jul 11 '13 at 15:22