public static IList<T> ConverToModels<T>(this DataTable table) where T : class, new()
{
// 定义返回集合
IList<T> list = new List<T>();
if (table.Rows.Count > 0)
{
string tempName = String.Empty;
// 循环每行数据
foreach (DataRow dr in table.Rows)
{
T t = new T(); // 创建实体,必须限制T 为可创建的对象 即:new()
PropertyInfo[] propertys = t.GetType().GetProperties(); // 获取泛型的所有属性
foreach (var item in propertys)
{
tempName = item.Name;
// 判断DataTable 中 是否包含当前列名
if (table.Columns.Contains(tempName))
{
// 判断当前属性是否可写 即:set
if (!item.CanWrite) continue;
// 获取该列名的值
object value = dr[tempName];
if (value != DBNull.Value)
{
// 赋值
item.SetValue(t, value, null);
}
}
}
}
}
return list;
}