List转换DataTable
1 public static class IListUtil 2 { 3 /// <summary> 4 /// 将集合类转换成DataTable 5 /// </summary> 6 /// <param name="list">集合</param> 7 /// <returns></returns> 8 public static DataTable AsDataTable<T>(this IList<T> list) 9 { 10 DataTable result = new DataTable(); 11 if (list.Count > 0) 12 { 13 PropertyInfo[] propertys = typeof(T).GetProperties(); 14 foreach (PropertyInfo pi in propertys) 15 { 16 result.Columns.Add(pi.Name, pi.PropertyType); 17 } 18 19 for (int i = 0; i < list.Count; i++) 20 { 21 ArrayList tempList = new ArrayList(); 22 foreach (var item in propertys) 23 { 24 object obj = item.GetValue(list[i], null); 25 tempList.Add(obj); 26 } 27 28 object[] array = tempList.ToArray(); 29 result.LoadDataRow(array, true); 30 } 31 } 32 return result; 33 } 34 35 36 }