Print out Linq Expression Tree Hierarchy
Asked Answered
H

1

15

The dynamic language runtime (DLR) has some pretty cool code for Expression's, including some very nice code to print out Expression trees which I want to use so that:

int a = 1;
int b = 2;
Expression<Func<int, int>> expression = (c) => a + (b * c)
expression.Evaluate(5, stringBuilder)

Outputs:

(5) => a + (b * c) = 11 Where
     a = 1
     b * c = 10 Where
          b = 2
          c = 5

I found some code on the net to do this but found that it only works if the expressiontakes in no arguments.

http://incrediblejourneysintotheknown.blogspot.com/2009/02/displaying-nested-evaluation-tree-from.html

I then discovered the DLR implementation of a similar method. However the DLR has its own custom implementations of the Expression class and many other standard C# types so I got a little confused. Anyone know how I can implement the above?

Hygro answered 30/3, 2009 at 14:29 Comment(0)
F
13

How about:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;

static class Program
{
    static void Main()
    {
        int a = 1, b = 2;
        StringBuilder sb = new StringBuilder();
        Expression<Func<int, int>> expression = (c) => a + (b * c);
        expression.Evaluate(sb, 5);
        // now fix the capture class names (from a and b)
        string s = sb.ToString();
        s = Regex.Replace(s, @"value\([^)]+\)\.", "");
        Console.WriteLine(s);
    }
    public static void Evaluate(this LambdaExpression expr, StringBuilder builder, params object[] args)
    {
        var parameters = expr.Parameters.ToArray();
        if (args == null || parameters.Length != args.Length) throw new ArgumentException("args");
        Evaluate(expr.Body, 0, builder, parameters, args);
    }
    private static StringBuilder Indent(this StringBuilder builder, int depth)
    {
        for (int i = 0; i < depth; i++) builder.Append("  ");
        return builder;
    }
    private static void Evaluate(this Expression expr, int depth, StringBuilder builder, ParameterExpression[] parameters, object[] args)
    {
        builder.Indent(depth).Append(expr).Append(" = ").Append(Expression.Lambda(expr, parameters).Compile().DynamicInvoke(args));

        UnaryExpression ue;
        BinaryExpression be;
        ConditionalExpression ce;

        if ((ue = expr as UnaryExpression) != null)
        {
            builder.AppendLine(" where");
            Evaluate(ue.Operand, depth + 1, builder, parameters, args);
        }
        if ((be = expr as BinaryExpression) != null)
        {
            builder.AppendLine(" where");
            Evaluate(be.Left, depth + 1, builder, parameters, args);
            Evaluate(be.Right, depth + 1, builder, parameters, args);                   
        }
        else if ((ce = expr as ConditionalExpression) != null)
        {
            builder.AppendLine(" where");
            Evaluate(ce.Test, depth + 1, builder, parameters, args);
            Evaluate(ce.IfTrue, depth + 1, builder, parameters, args);
            Evaluate(ce.IfFalse, depth + 1, builder, parameters, args);
        }
        else
        {
            builder.AppendLine();
        }
    }

}
Filing answered 31/3, 2009 at 6:51 Comment(2)
In above code methods .Evaluate and .Indent are not recognized by my VS2012. What do I need to install or add reference to?Neron
This is an old question, but to answer user3057544, it's probably better to put this in a static class and reference it as an extension method off of a LambdaExpression... or at least use it in a static class as Marc does above.Rankle

© 2022 - 2024 — McMap. All rights reserved.