Replace a type in an expression tree

后端 未结 1 1471
太阳男子
太阳男子 2021-02-06 17:38

I\'m struggling with the modification of an expression tree. I\'ve simplified the example to make it easier to display here. Let\'s start with two classes:

    p         


        
1条回答
  •  伪装坚强ぢ
    2021-02-06 18:01

    After some more searching I found the answer here: How to change a type in an expression tree?. It didn't show up in the suggestions when I submitted my question.

    As I don't really need the Filter class, I instead created an interface with only the properties that I want to be able to filter (IEntity) and modified the Entity class to implement it. Now I'm able to get the desired results with this:

    // Example use: return entities.Entities.Where(ExpressionTransformer.Transform(filter));
    internal static class ExpressionTransformer where TTo : TFrom
    {
        public class Visitor : ExpressionVisitor
        {
            private ParameterExpression _parameter;
    
            public Visitor(ParameterExpression parameter)
            {
                _parameter = parameter;
            }
    
            protected override Expression VisitParameter(ParameterExpression node)
            {
                return _parameter;
            }
        }
    
        public static Expression> Tranform(Expression> expression)
        {
            ParameterExpression parameter = Expression.Parameter(typeof(TTo));
            Expression body = new Visitor(parameter).Visit(expression.Body);
            return Expression.Lambda>(body, parameter);
        }
    }
    

    In case you need to do something similar but you cannot work with an interface or you cannot make your class implement that interface: the answer is also in the above mentioned answer

    0 讨论(0)
提交回复
热议问题