Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Function to get full path of nested object property #14

Open
manni497 opened this issue Oct 11, 2023 · 0 comments
Open

Function to get full path of nested object property #14

manni497 opened this issue Oct 11, 2023 · 0 comments
Labels
enhancement New feature or request

Comments

@manni497
Copy link
Collaborator

manni497 commented Oct 11, 2023

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;
        }
@drebrez drebrez added the enhancement New feature or request label Jan 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants