1 /// <summary>
2 /// 将集合类转换成DataTable
3 /// </summary>
4 /// <param name="list">集合</param>
5 /// <returns></returns>
6 public static DataTable ToDataTable(IList list)
7 {
8 DataTable result = new DataTable();
9 if (list.Count > 0)
10 {
11 PropertyInfo[] propertys = list[0].GetType().GetProperties();
12 foreach (PropertyInfo pi in propertys)
13 {
14 result.Columns.Add(pi.Name, pi.PropertyType);
15 }
16 for (int i = 0; i < list.Count; i++)
17 {
18 ArrayList tempList = new ArrayList();
19 foreach (PropertyInfo pi in propertys)
20 {
21 object obj = pi.GetValue(list, null);
22 tempList.Add(obj);
23 }
24 object[] array = tempList.ToArray();
25 result.LoadDataRow(array, true);
26 }
27 }
28 return result;
29 }
30 /**//// <summary>
31 /// 将泛型集合类转换成DataTable
32 /// </summary>
33 /// <typeparam name="T">集合项类型</typeparam>
34 /// <param name="list">集合</param>
35 /// <returns>数据集(表)</returns>
36 public static DataTable ToDataTable<T>(IList<T> list)
37 {
38 return ConvertX.ToDataTable<T>(list, null);
39 }
40 /**//// <summary>
41 /// 将泛型集合类转换成DataTable
42 /// </summary>
43 /// <typeparam name="T">集合项类型</typeparam>
44 /// <param name="list">集合</param>
45 /// <param name="propertyName">需要返回的列的列名</param>
46 /// <returns>数据集(表)</returns>
47 public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
48 {
49 List<string> propertyNameList = new List<string>();
50 if (propertyName != null)
51 propertyNameList.AddRange(propertyName);
52 DataTable result = new DataTable();
53 if (list.Count > 0)
54 {
55 PropertyInfo[] propertys = list[0].GetType().GetProperties();
56 foreach (PropertyInfo pi in propertys)
57 {
58 if (propertyNameList.Count == 0)
59 {
60 result.Columns.Add(pi.Name, pi.PropertyType);
61 }
62 else
63 {
64 if (propertyNameList.Contains(pi.Name))
65 result.Columns.Add(pi.Name, pi.PropertyType);
66 }
67 }
68 for (int i = 0; i < list.Count; i++)
69 {
70 ArrayList tempList = new ArrayList();
71 foreach (PropertyInfo pi in propertys)
72 {
73 if (propertyNameList.Count == 0)
74 {
75 object obj = pi.GetValue(list, null);
76 tempList.Add(obj);
77 }
78 else
79 {
80 if (propertyNameList.Contains(pi.Name))
81 {
82 object obj = pi.GetValue(list, null);
83 tempList.Add(obj);
84 }
85 }
86 }
87 object[] array = tempList.ToArray();
88 result.LoadDataRow(array, true);
89 }
90 }
91 return result;
92 }