【发布时间】:2014-09-17 11:35:05
【问题描述】:
我创建了一个扩展方法来将数据表转换为列表并将列表转换为数据表。我对此有多个问题。有人可以帮我解决问题吗:
- 数据表列和通用类属性名称需要相同且区分大小写。我需要修改它以处理不考虑大小写的情况,例如:EmployeeName = employeename。
- 如果泛型类具有复杂类型作为属性,那么我的函数似乎不起作用。例如:如果我有公共字符串 EmployeeName {get; set;} 我的代码有效,但如果我有 Public Department DepartmentDetails {get; set;}(知道这个有点棘手,但如果有人能给我一个如何处理这个问题的建议,我会很高兴的。)
请在下面找到我的扩展方法。
public static List<T> ToList<T>(this DataTable table) where T : new()
{
try
{
var dataList = new List<T>();
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic;
var propertyList = (from PropertyInfo property in typeof(T).GetProperties(flags)
select new
{
Name = property.Name,
Type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType
}).ToList();
var dataTableFieldNames = (from DataColumn columnHeader in table.Columns
select new { Name = columnHeader.ColumnName, Type = columnHeader.DataType }).ToList();
var commonProperties = propertyList.Intersect(dataTableFieldNames).ToList();
foreach (DataRow dataRow in table.AsEnumerable().ToList())
{
var templateType = new T();
foreach (var field in commonProperties)
{
PropertyInfo propertyInfos = templateType.GetType().GetProperty(field.Name);
propertyInfos.SetValue(templateType, dataRow[field.Name], null);
}
dataList.Add(templateType);
}
return dataList;
}
catch (Exception ex)
{
throw;
}
}
非常感谢任何帮助。干杯!!!
【问题讨论】:
标签: c# .net datatable extension-methods