0

I'm working on something similar to a text templating engine.
I'm providing metadata from my server to the client to represent an javascript version of the access path for instance:

Say I have a DTO:

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

I have a mapping on the server which looks like so:

Expression<Func<Employee, string>> firstNameExpression = e => employee.FirstName;

When returned to the client I would like to return something similar a string representation of the expression

$"{nameof(Employee)}.{nameof(Employee.FirstName)}";

I would prefer not to have to parse the expression manually or walk the expression tree.

//e.g Pseudo Code

LambdaExpression expression
if(expression is MemberExpression expr)
{
   stringBuilder.Prepend(expr.Body.Member.Name)
}
//... Handle errors 

Is there a simple way to output and expression as if it were written in code in some way?

1 Answer 1

1

If you need to precisely serialize/deserialize the expression tree, Serialize.Linq library might help.

If all you want is some kind of string representation for display purposes, then I would recommend the ExpressionTreeToString library that I've written:

using ExpressionTreeToString;

Console.WriteLine(firstNameExpression.ToString("C#"));
/*
    e => e.FirstName
*/

Console.WriteLine(firstNameExpression.ToString("Textual tree", "C#"));
/*
    Lambda (Func<Employee, string>)
        · Parameters[0] - Parameter (Employee) e
        · Body - MemberAccess (string) FirstName
            · Expression - Parameter (Employee) e
*/

There are various string representations available.

(Disclaimer: I am the author of the latter library.)

Sign up to request clarification or add additional context in comments.

1 Comment

I ended up working around the original problem, but this library looks like it would solve my problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.