datatable轉list

public static List<T> TableToList<T>(DataTable dt, bool isStoreDB = true)
{
List<T> list = new List<T>();
Type type = typeof(T);
//List<string> listColums = new List<string>();
PropertyInfo[] pArray = type.GetProperties(); //集合屬性數組
foreach (DataRow row in dt.Rows)
{
T entity = Activator.CreateInstance<T>(); //新建對象實例
foreach (PropertyInfo p in pArray)
{
if (!dt.Columns.Contains(p.Name) || row[p.Name] == null || row[p.Name] == DBNull.Value)
{
continue; //DataTable列中不存在集合屬性或者字段內容爲空則,跳出循環,進行下個循環
}
if (isStoreDB && p.PropertyType == typeof(DateTime) && Convert.ToDateTime(row[p.Name]) < Convert.ToDateTime("1753-01-01"))
{
continue;
}
try
{
if (p.PropertyType == typeof(Nullable<decimal>))
{
var obj = Convert.ToDecimal(row[p.Name]);//類型強轉,將table字段類型轉爲集合字段類型
p.SetValue(entity, obj, null);
}
else
{
var obj = Convert.ChangeType(row[p.Name], p.PropertyType);//類型強轉,將table字段類型轉爲集合字段類型
p.SetValue(entity, obj, null);
}

}
catch (Exception e)
{
//throw e;
}

}
list.Add(entity);
}
return list;
}數組

相關文章
相關標籤/搜索