DataTable 转为List<T>集合

public static List<T> HubbleTableToList<T>(this DataTable dt) where T:Class
{
List<T> _list = new List<T>();
if (dt == null) return _list;
T model;
foreach (DataRow dr in dt.Rows)//进行循环dataTable行数据
{
model = Activator.CreateInstance<T>();//获取泛型类型的新实例
foreach (DataColumn dc in dr.Table.Columns)//循环该行的列
{
object drValue = dr[dc.ColumnName];//根据列名获取行数据
PropertyInfo pi = model.GetType().GetProperty(dc.ColumnName);//model.GetType()表示获取model的类型,GetProperty()获取指定名称的公共属性,其中需要引用using System.Reflection;
if (pi != null && pi.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
{
if (pi.PropertyType == typeof(int)||pi.PropertyType==typeof(int?))//注:如果未加此判断,则会出现 类型“System.Int64”的对象无法转换为类型“System.Int32”。的错误
{
drValue = Convert.ToInt32(drValue);
}
pi.SetValue(model, drValue, null);
}
}
 
_list.Add(model);
 
}
return _list;
}
原文地址:https://www.cnblogs.com/97310ZT/p/8580682.html