Search code examples
c#linqlambdaexpressionexpression-trees

How to reconstruct linq expression tree


How to inspect linq expression tree, so it could be rebuilt statement by statement (using System.Linq.Expressions.Expression methods)? I'm using DebugView from VS17 to visualise expression, but it's not very user friendly to read. Maybe there are better options?


Solution

  • (Disclaimer: I am the author of the library in question.)

    Using the ExpressionTreeToString library, available on NuGet, you can call the ToString extension method on an expression:

    // using ExpressionToString
    Expression<Func<string, int, string>> expr = (s, i) => $"{s}, {i}";    
    Console.WriteLine(expr.ToString("Factory methods"));
    

    and get back output like the following:

    // using static System.Linq.Expressions.Expression
    
    Lambda(
        Call(
            typeof(string).GetMethod("Format"),
            Constant("{0}, {1}"), s,
            Convert(i,
                typeof(object)
            )
        ),
        var s = Parameter(
            typeof(string),
            "s"
        ),
        var i = Parameter(
            typeof(int),
            "i"
        )
    )
    

    For details on the syntax used by the DebugView property, see DebugView syntax.