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

时间:2018-10-05 10:43:51

标签: c# .net linq linq-expressions

我想创建一个返回字典的方法,如下所示。但是,我想成为通用的方法,将其解释为EntityType和columnNameList。我想这样打,

我的方法调用:

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

我的返回值

 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;
}

1 个答案:

答案 0 :(得分:3)

引用be compatible with

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

例如,以下示例使用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;
}