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