我想创建一个返回字典的方法,如下所示。但是,我想成为通用的方法,将其解释为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;
}
答案 0 :(得分:3)
使用Expression
类及其静态工厂方法,根据泛型参数类型中提供的成员名称,手动构建所需的表达式。
例如,以下示例使用Parameter
和Property
工厂方法为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;
}