C#將list轉換為datatable


 1 DataTable dt = new DataTable();
 2 if (_list != null)
 3 {
      //通過反射獲取list中的字段 
4 System.Reflection.PropertyInfo[] p = _list[0].GetType().GetProperties(); 5 foreach (System.Reflection.PropertyInfo pi in p) 6 { 7 dt.Columns.Add(pi.Name, System.Type.GetType(pi.PropertyType.ToString())); 8 } 9 for (int i = 0; i < _list.Count; i++) 10 { 11 IList TempList = new ArrayList(); 12 //將IList中的一條記錄寫入ArrayList 13 foreach (System.Reflection.PropertyInfo pi in p) 14 { 15 object oo = pi.GetValue(_list[i], null); 16 TempList.Add(oo); 17 } 18 object[] itm = new object[p.Length]; 19 for (int j = 0; j < TempList.Count; j++) 20 { 21 itm.SetValue(TempList[j], j); 22 } 23 dt.LoadDataRow(itm, true); }
24 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM