Last active
December 29, 2018 20:01
-
-
Save hidegh/c2110ad8308c52e0f04f484b7d378ce5 to your computer and use it in GitHub Desktop.
"Unifies" the expression, so we get same result if same expression is used (with different base parameter name)...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq.Expressions; | |
/// <summary> | |
/// Usage: | |
/// var exp1 = (Expression<Func<Person, string>>) exp1 = i => i.Addresses[0].City; | |
/// var exp2 = (Expression<Func<Person, string>>) exp1 = j => j.Addresses[0].City; | |
/// var exp1String = new ExpressionInitialParameterRenamer().Rename(exp1).ToString(); | |
/// /// </summary> | |
namespace ExpressionHelper | |
{ | |
public class ExpressionInitialParameterRenamer : ExpressionVisitor | |
{ | |
string originalName = ""; | |
string renameTo = ""; | |
public Expression Rename(Expression expression, string renameTo = "i") | |
{ | |
this.renameTo = renameTo; | |
var lambdaExpression = expression as LambdaExpression; | |
if (lambdaExpression == null) | |
throw new NotSupportedException("Must be a lambda expression"); | |
if (lambdaExpression.Parameters.Count == 0) | |
{ | |
return expression; | |
} | |
else | |
{ | |
originalName = lambdaExpression.Parameters[0].Name; | |
if (renameTo == originalName) | |
return expression; | |
return Visit(expression); | |
} | |
} | |
protected override Expression VisitParameter(ParameterExpression node) | |
{ | |
if (node.Name == originalName) | |
return Expression.Parameter(node.Type, renameTo); | |
else | |
return node; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment