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:
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
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
}
?