DataTable 转为ListT集合
生活随笔
收集整理的這篇文章主要介紹了
DataTable 转为ListT集合
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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)//進(jìn)行循環(huán)dataTable行數(shù)據(jù) { model = Activator.CreateInstance<T>();//獲取泛型類型的新實(shí)例 foreach (DataColumn dc in dr.Table.Columns)//循環(huán)該行的列 { object drValue = dr[dc.ColumnName];//根據(jù)列名獲取行數(shù)據(jù) 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?))//注:如果未加此判斷,則會(huì)出現(xiàn) 類型“System.Int64”的對(duì)象無法轉(zhuǎn)換為類型“System.Int32”。的錯(cuò)誤 { drValue = Convert.ToInt32(drValue); } pi.SetValue(model, drValue, null); } } _list.Add(model); } return _list; }
轉(zhuǎn)載于:https://www.cnblogs.com/97310ZT/p/8580682.html
總結(jié)
以上是生活随笔為你收集整理的DataTable 转为ListT集合的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天玑9000+首次下放中端 iQOO N
- 下一篇: 软件建模——第3章 项目前期