-
Notifications
You must be signed in to change notification settings - Fork 7
Open
Labels
enhancementNew feature or requestNew feature or request
Description
Implement a function that given an expression returns the path in the object like:
// Act
string actual = ExpressionUtils.PathOf<ExpressionUtilsTests>(x => x.Recursion.Recursion.Recursion.Recursion);
// Assert
actual.ShouldBe("Recursion.Recursion.Recursion.Recursion");
C# implementation
public static string PathOf<T>(Expression<Func<T, object>> expression)
{
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
Stack<string> memberNames = new Stack<string>();
MemberExpression memberExp = GetMemberExpression(expression.Body);
while (memberExp != null)
{
memberNames.Push(memberExp.Member.Name);
memberExp = GetMemberExpression(memberExp.Expression);
}
return string.Join(".", memberNames);
}
public static MemberExpression GetMemberExpression(Expression toUnwrap)
{
if (toUnwrap is UnaryExpression unaryExpression)
{
return unaryExpression.Operand as MemberExpression;
}
return toUnwrap as MemberExpression;
}
Copilot
Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or request