How to create lambda expression that returns object's property, having this property's name?

后端 未结 2 1890
清酒与你
清酒与你 2021-01-22 09:39

I am completely lost on this one. I have a piece of code that does what I need when implemented like this:

return filters.Add(m => m.Metadata.RecordId).IsEqua         


        
2条回答
  •  醉酒成梦
    2021-01-22 10:35

    I'm not sure what exactly you want there as an output (bool, int and comparing),
    But this should get you on the right track...

    public static void Test(string propertyPath)
    {
        var props = propertyPath.Split('.');
        Expression parameter = Expression.Parameter(typeof(TestObj), "x");
        Expression property = parameter;
        foreach (var propertyName in props)
            property = Expression.Property(property, propertyName);
        Expression> lambdaExpression =
            Expression.Lambda>(property, parameter as ParameterExpression);
        Add(lambdaExpression);
    }
    static void Add(Expression> paramExp)
    {
        TestObj obj = new TestObj { Metadata = new Metadata { RecordId = 1, Name = "test" } };
        var id = paramExp.Compile()(obj);
    }
    

    And you can also check this post of Jon's which nicely describes how that works...
    Use reflection to get lambda expression from property Name

提交回复
热议问题