0

Given

Expression<Func<SubType, PropertyType>> selector = subType => subtype.[...].Property

I want to extend another MemberExpression which provide SubType like this:

var parameter = Expression.Parameter(typeof(ParentType), "parameter");
var subTypeProperty = Expression.Property(parameter, nameof(ParentType.SubType));

To produce another MemberExpression which starts from ParentType, traverse same path as first selector expression and provides an MemberExpression like:

parentType.SubType.[...].Property

How can I do this?

jps
  • 20,041
  • 15
  • 75
  • 79
Soheil
  • 99
  • 1
  • 10

1 Answers1

-1

Actually this link provide good explanation and solution for my question

using ExpressionVisitor you can traverse first selector, looking for parameter expressions and replace all parameter expressions with "subTypeProperty" MemberExpession

using:

public class ReplaceVisitor : ExpressionVisitor
{
    private readonly Expression from, to;

    public ReplaceVisitor(Expression from, Expression to)
    {
        this.from = from;
        this.to = to;
    }

    public override Expression Visit(Expression node)
    {
        return node == from ? to : base.Visit(node);
    }
}

then:

var newSelector = new ReplaceVisitor(selector.Parameters.First(), subTypeProperty)
            .Visit(selector.Body);
Soheil
  • 99
  • 1
  • 10