Let's say I have an expression like this:
Expression<Predicate<T>> exp
If I assign the following expression:
a => a.First() != 0
and then I call exp.ToString()
I will obtain exactly the expression I passed, that is perfectly good, but, suppose we want to change the name we use for 'a' with something else, how can we do ?
String replacement would not do in all the case ( it works in the example above,but what if the parameter was called 'i' for example ?)
Is it possible to have just the parameter name replacement, run time, without affecting the expression semantic ?
UPDATE The @PhilKlein works perfectly, but requires framework 4. But if we need to target the framework 3.5 we can use an ExpressionVisitor class from Matt Warren, by just modifing from protected to public the Visit method.
Typically I would use a refactoring tool, such as Jetbrains Resharper to do so. It has a feature "Refactor, Rename" which lets you do just that, and knows the difference between a string replace and a variable rename. I know of no such feature from within Visual Studio itself. http://www.jetbrains.com/resharper/
If you are referring to building a dynamic expression, however, and want to change the parameter, you can use code such as the following (copied from: c# List<string> to Lambda Expression with starter example: Refactor to handle the List)
And to change the parameter from "x" to "y", we could do the following:
Expressions are immutable so, therefore, you cannot modify them, you would need to construct new tree.
In .NET 4.0, there is a class which can help you significantly, see ExpressionVisitor
You can do:
and then,
new Renamer().Rename(exp).ToString()
should hold what you expect.It's quick and dirty, but assuming you're using .NET 4.0 you could create the following:
And then use it as follows: