Dynamic expression from a class object property

I am starting to learn dynamic expressions, so please help me solve one problem. I have an object

    public class Categorisation{
       string Name{get;set;}
    }

    public class Client{
       public Categorisation Categorisation{get;set;}
}

All I need to do is write a dynamic expression and call Categorization. Name .Equals ("A1") from the Client object.

x=>x.Categorisation.Name.Equals("A1")

How to 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 incorrect, and I call the Equals method from the categorization property, and not from the categorization name. But how to call the Name property?

+1
source share
1 answer
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);
+2
source

Source: https://habr.com/ru/post/1546550/


All Articles