您的位置:首页 > 编程语言

【代码】DataTable转换成List<T>集合

2014-03-07 10:14 393 查看
粗略的版本。

public class DataTableToList<T> where T : class, new()
{
/// <summary>
/// DataTable转换成Model对象。
/// 2014年3月4日15:49:00
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public static List<T> GetModelList(DataTable table)
{
List<T> list = new List<T>();
foreach (DataRow item in table.Rows)
{
// 根据泛型创建实例
T t = Activator.CreateInstance<T>();
// 获得此模型的公共属性
PropertyInfo[] propertyInfos = t.GetType().GetProperties();
foreach (var propertyInfo in propertyInfos)
{
string tempName = propertyInfo.Name;
if (table.Columns.Contains(tempName))
{
if (!propertyInfo.CanWrite) continue;
object value = item[tempName];
if (value != DBNull.Value)
propertyInfo.SetValue(t, value, null);
}
}
list.Add(t);
}
return list;
}
}


调用。

DataTable table = dbHelper.Query(sqlstr).Tables[0];
List<InvInventoryLog> list = DataTableToList<InvInventoryLog>.GetModelList(table);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# 代码