Skip to content

Function to get full path of nested object property #14

@manni497

Description

@manni497

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;
        }

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions