vendredi 10 avril 2020

How to create LamndaExpression from string variables using c#

I have a string variable which contains the property name of a class. I would like to create a method which should return Expression<Func<T,Tkey>> where T is the class name and TKey is the type of the property which belongs to T. See below an example

public class Person 
{
    public int Age {get; set;}
    public String Name {get; set;}
}

The method should work like below:

var ageExp = ExpressionExtensions.GetExpression<Person>("age"); // expected Expression<Func<int>>
var nameExp = ExpressionExtensions.GetExpression<Person>("name"); // expected Expression<Func<string>>

I need help to write the following method

public class ExpressionExtensions
{
     public static Expression<TDelegate> GetExpression<T>(string propName)
     {
          // conversion code
     }
}




Aucun commentaire:

Enregistrer un commentaire