UPDATE:
I'll try to explain what I mean. There are 2 different classes (MyClass1 and MyClass2) and method to convert class1 to class2:
class MyClass1
{
//...Some fields and properties
}
class MyClass2
{
//...Some fields and properties
}
public MyClass2 Convert(MyClass1 class1)
{
//.....
return class2Object;
}
There are 2 different methods:
void method1(Expression<Func<MyClass1, bool>> where, //other parameters)
{
//some operations
//...............
//need to call method2(Expression<Func<MyClass2, bool>>)
// BUT! How do I convert Expression<Func<MyClass1, bool>>
// to Expression<Func<MyClass2, bool>>
}
void method2(Expression<Func<MyClass2, bool>> where, //other parameters)
{
//some operations
}
How do I convert Expression< Func< MyClass1, bool>> to Expression< Func< MyClass2, bool > >
Expression trees are immutable, so to do this ou would need to walk the entire tree, rebuilding it and substiting any uses of the type with the equivalent - usually by writing a "visitor". When encountering a MemberExpression or MethodCallExpression, you would check the member's declaring type - if it is the one ou don't want, recreate it (Expression.PropertyOrField is useful here).
Note that you can't do this just at the places it is used; the entire tree must be regenerated. I'm not at a PC at the moment, but if you want I can do an example later; leave a comment if you need this example.
Note that this is somewhat complicated by the int/long and char/string mismatch.
Let me guess what you are asking: Your
MyClass1
andMyClass2
look the same (they both have an int field1 and a string field2). Now you have anExpression<Func<MyClass1,bool>>
, something like:And you want another expression, which looks the same, but it's for
MyClass2
:If this is what you are asking, here is my answer:
To get the expression for
MyClass2
, you need to replace allx
inexp1
, because allx
in exp1 are of typeMyClass1
. ExpressionVisitor is exactly what you want.The visitor will go through(say "visit") the whole expression, visit all the nodes. When it comes to an
ParameterExpression
node, we change the node (because it's MyClass1, we change it to MyClass2, see VisitParameter method). Another thing we need to change is, when the visitor comes to a node likex.field1
, it's visiting the field1 inMyClass1
, we need to modify it too(see VisitMember). After going through the whole exp1, we get a totally new exp2, with some nodes replaced, that's what we want.You could compile the first expression to a delegate and then convert it with
NJection.LambdaConverter which is a library that converts delegates to expression trees.