您的位置:首页 > 运维架构 > 网站架构

.NET基础架构方法—DataTableToList通用方法

2016-07-19 22:34 671 查看
.NET架构基础方法—DataTableToList通用方法

我们经常需要将从数据库中所读取的数据以DataTable类型返回,也经常需要遍历DataTable转换为List<T>。我们也经常需要为每一个DataTable转换为List单独编写适合他们数据库架构地方法。下面上代码:

public static class DataTableTools<T> where T : class, new()
{
public static List<T> DataTableToList(DataTable dt)
{
List<T> list = null;
var rowCount = dt.Rows.Count;
if (rowCount > 0)
{
list = new List<T>();
int i;
for (i = 0; i < rowCount; i++)
{
T model = DataRowToModel(dt.Rows[i]);
list.Add(model);
}
}
return list;
}
private static T DataRowToModel(DataRow dr)
{
T model = new T();
var propertiesCount = typeof(T).GetProperties().Length;
for (int j = 0; j < propertiesCount; j++)
{
PropertyInfo propertyInfo = GetModelPropertyInfo(model, dr.Table.Columns[j]);
if (propertyInfo != null && dr[j] != DBNull.Value)
{
propertyInfo.SetValue(model, dr[j]);
}
}
return model;
}
private static PropertyInfo GetModelPropertyInfo(T model, DataColumn column)
{
string propertyName = column.ColumnName;
return model.GetType().GetProperty(propertyName);
}
}


代码中同样需要遍历DataTable,从而把DataTable中的每一行DataRow先转换为T类型的Model。在这里,我们根据每一行数据的数据架构来获取该行的每一列的ColumnName。我们也正是根据此ColumnName来获取泛型T的属性—GetModelPropertyInfo()方法,在其中通过SetValue设置该model的该属性值。也正是使用行数据架构的列属性名称来获取泛型T的属性,所以一定要保证泛型T的属性名称和数据架构名称相同,也只有这样才能使用该通用方法。

相信大牛们早已经掌握了这样的方法,如果有什么提议欢迎指出。如果你学会了,请为自己点赞,也是为我点赞。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: