I have two lambda expressions:
Expression<Func<MyEntity, bool>> e1 = i = >i.FName.Contain("john");
and
Expression<Func<MyEntity, bool>> e2 = i => i.LName.Contain("smith");
the i type, comes from my poco entities, that can’t used with invoke. I want to combine these in runtime.
I want to combine these expressions in runtime in a similar way as:
Expression<Func<MyEntity, bool>> e3 = Combine(e1,e2);
The problem is that you can’t just “and”/”or” them, because you need to re-write the internals to change the parameters; if you use the
.Bodyfrome1, but the parameter frome2, it won’t work – because the.Bodyofe1references a completely unrelated parameter instance that isn’t defined. This is more obvious if you use:(note the difference between
e1usingiande2usingj)If we combine them without rewriting the parameter, we would get the nonsensical:
(woah…. where did
jcome from?)HOWEVER; the problem is identical regardless of the name of the parameter: it is still a different parameter.
And since the expression is immutable you can’t just swap it “in place”.
The trick is to use a “visitor” to rewrite the nodes, like so: