DataTable 转为ListT集合
生活随笔
收集整理的這篇文章主要介紹了
DataTable 转为ListT集合
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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
總結
以上是生活随笔為你收集整理的DataTable 转为ListT集合的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天玑9000+首次下放中端 iQOO N
- 下一篇: 软件建模——第3章 项目前期