Reputation: 2100
i'm starting to explore dynamic expressions, so please help me to solve one issue. I have an object
public class Categorisation{
string Name{get;set;}
}
public class Client{
public Categorisation Categorisation{get;set;}
}
All I need is to write a dynamic expression and call Categorisation.Name.Equals("A1") from Client object.
x=>x.Categorisation.Name.Equals("A1")
How can I do this using Expressions?
var param = Expression.Parameter(typeof(Client));
var prop = Expression.Property(param, typeof(Client).GetProperty("Categorisation"));
var argument = Expression.Constant("A1");
var method = typeof(string).GetMethod("Equals", new[] { typeof(string) });
var call = Expression.Call(prop, method);
var expr = Expression.Lambda<Func<Client, bool>>(call, param);
Of course this code is wrong and I call method Equals from Categorisation property and not from Name of Categorisation. But how to invoke Name property?
Upvotes: 1
Views: 1227
Reputation: 144126
var param = Expression.Parameter(typeof(Client));
var prop = Expression.Property(param, typeof(Client).GetProperty("Categorisation"));
var namePropExpr = Expression.Property(prop, "Name");
var argument = Expression.Constant("A1");
var method = typeof(string).GetMethod("Equals", new[] { typeof(string) });
var call = Expression.Call(namePropExpr, method, argument);
var expr = Expression.Lambda<Func<Client, bool>>(call, param);
Upvotes: 2