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 }
不积跬步,无以至千里!