I want to combine two LambdaExpressions without compiling them.
This is what it looks like if I do compile them:
public Expression<Func<TContainer,bool>> CreatePredicate<TContainer,TMember>(
Expression<Func<TContainer,TMember>> getMemberExpression,
Expression<Func<TMember,bool>> memberPredicateExpression)
{
return x => memberPredicateExpression.Compile()(getMemberExpression.Compile()(x));
}
That's obviously not the fastest way to get the target expression from the provided arguments. Also, it makes it incompatible with query providers like LINQ to SQL that do not support C# method calls.
From what I've read it seems like the best approach is to build an ExpressionVisitor
class. However, this seems like it could be a pretty common task. Does anyone know of an existing open source code base that provides this kind of functionality? If not, what is the best way to approach the ExpressionVisitor
to make it as generic as possible?
I don't know if it's the best way, but you could do something like that:
Usage:
Result:
I guess it would be better to get something like
x => x.Bar % 2 == 0
, but it would probably be significantly harder...EDIT: actually it wasn't so hard with an expression visitor:
It gives the following expression: