Skip to content

Instantly share code, notes, and snippets.

@hidegh
Last active December 29, 2018 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hidegh/c2110ad8308c52e0f04f484b7d378ce5 to your computer and use it in GitHub Desktop.
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)...
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