Construct LambdaExpression for nested property from string

前端 未结 2 744
旧时难觅i
旧时难觅i 2020-11-30 23:09

I am trying to create a lambda expression for a nested property at run-time from the name of the propert. Basically I am trying to create the lambda expression specified by:

相关标签:
2条回答
  • 2020-11-30 23:26

    To construct a lambda expression but with an inline solution you can do:

    var param = Expression.Parameter(typeOf(FooBar), "x");
    
    // you "concat" your expression here :
    var propertyExpression = Expression.PropertyOrField(param, "myBar");
    propertyExpression = Expression.PropertyOrField(propertyExpression, "name");
    // expected result : "x.myBar.name" as a body expression
    
    var expression = Expression.Lambda(propertyExpression, param);
    // x => x.myBar.name
    
    0 讨论(0)
  • 2020-11-30 23:37

    Do you mean:

    static LambdaExpression CreateExpression(Type type, string propertyName) {
        var param = Expression.Parameter(type, "x");
        Expression body = param;
        foreach (var member in propertyName.Split('.')) {
            body = Expression.PropertyOrField(body, member);
        }
        return Expression.Lambda(body, param);
    }
    

    For example:

    class Foo {
        public Bar myBar { get; set; }
    }
    class Bar {
        public string name { get; set; }
    }
    static void Main() {
        var expression = CreateExpression(typeof(Foo), "myBar.name");
        // x => x.myBar.name
    }
    

    ?

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