Hemant Malpote
Hemant Malpote

Reputation: 891

How to get values in expression

I am having expression s => s.Application.Id

I want to get Application.Id.

As expression can be vary in next case to

s=s.Application.ApplicationType.Id

in this case i want Application.ApplicationType.Id

I had try with expression.body.member.name

It gives me Id.

Upvotes: 0

Views: 67

Answers (2)

Sergey Litvinov
Sergey Litvinov

Reputation: 7458

You can parse it with ExpressionVisitor that just remembers parameter expression and cuts it from the begginging like this:

using System;
using System.Linq.Expressions;

public class Program
{
    public static void Main()
    {
        Expression<Func<Parent, int>> expression = s => s.Application.ID;

        var val = new CustomVisitor().ConvertToString(expression);

        Console.WriteLine("expression is " + val);
    }
}

public class CustomVisitor : ExpressionVisitor
{
    private ParameterExpression _param;

    private Expression _body;

    protected override Expression VisitLambda<T>(Expression<T> node)
    {
        _body = node.Body;
        return base.VisitLambda(node);
    }

    protected override Expression VisitParameter(ParameterExpression node)
    {
        _param = node;
        return node;
    }

    public string ConvertToString(Expression expression)
    {
        Visit(expression);

        var parameterLength = _param.Name.Length + 1; // cuts name plus dot
        return _body.ToString().Substring(parameterLength);
    }
}

public class Parent
{
    public Application Application {get;set;}
}

public class Application
{
    public int ID {get;set;}
}

Here is working sample on DotNetFiddle - https://dotnetfiddle.net/Fmye6z

Upvotes: 1

John
John

Reputation: 3702

No need to compile or anything fancy. Just walk the expression tree recursively to assemble the full path.

class Program
{
    static void Main(string[] args)
    {
        string path = GetPropertyName<Test>(x => x.Test2.Application.Id);
    }

    static string GetPropertyName<T>(Expression<Func<T, object>> expression)
    {
        var memberExpression = (MemberExpression)expression.Body;
        return GetMemberExpressionPath(memberExpression);
    }

    static string GetMemberExpressionPath(MemberExpression exp)
    {
        string s = null;

        var rootExp = exp.Expression as MemberExpression;
        if (rootExp != null)
        {
            s = GetMemberExpressionPath(rootExp);
        }

        //var paramExp = exp.Expression as ParameterExpression;
        //if (paramExp != null)
        //{
        //    s = paramExp.Name;
        //}

        return (s != null ? s + "." : "") + exp.Member.Name;
    }

}

Upvotes: 0

Related Questions