创建一个创建动态表达式的方法

Create a method which create dynamic expression

我想创建一个 return 字典的方法,如下所示。但是,我想成为参数为 EntityType 和 columnNameList 的通用方法。我想这样打电话,

我的方法调用:

CreateColumnMap<Student>(new List<string>{"Name","Surname","Age"});

我的return值

 var columnsMap = new Dictionary<string, Expression<Func<Student, object>>>()
                    {
                      ["Name"] = v => v.Name,
                      ["Surname"] = v => v.Surname,
                      ["Age"] = v => v.Age
                    };

Student.cs

public class Student
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Age { get; set; }
    public string SchoolName { get; set; }
}

我开始了如下功能。但我无法完成。我怎样才能完成“???”部分。

public Dictionary<string, Expression<Func<T, object>>> CreateColumnMap<T>(List<string> columNameList)
{
    var dictionary = new Dictionary<string, Expression<Func<T, object>>>();
    foreach (var columnName in columNameList)
    {
        //??????
        dictionary.Add(); //????????????????????
        //??????
    }
    return dictionary;
}

引用Creating Expression Trees by Using the API

使用 Expression class 及其静态工厂方法根据提供的泛型参数类型的成员名称手动构建所需的表达式。

例如下面使用ParameterProperty工厂方法手动构建lambda表达式v => v.PropertyName

的表达式树节点
Expression<Func<TModel, object>> GetPropertyExpression<TModel>(string propertyName) {
    // Manually build the expression tree for 
    // the lambda expression v => v.PropertyName.

    // (TModel v) =>
    var parameter = Expression.Parameter(typeof(TModel), "v");
    // (TModel v) => v.PropertyName
    var property = Expression.Property(parameter, propertyName);

    var expression = Expression.Lambda<Func<TModel, object>>(property, parameter);
    return expression;
}

然后您可以应用以上内容

public Dictionary<string, Expression<Func<T, object>>> CreateColumnMap<T>(List<string> columNameList) {
    var dictionary = new Dictionary<string, Expression<Func<T, object>>>();
    foreach (var columnName in columNameList) {            
        dictionary[columnName] = GetPropertyExpression<T>(columnName);
    }
    return dictionary;
}