list转datatable

 1 public static DataTable ToDataTable<T>(IList<T> list)
 2         {
 3             return ToDataTable<T>(list, null);
 4         }
 5 public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
 6         {
 7             List<string> propertyNameList = new List<string>();
 8             if (propertyName != null)
 9                 propertyNameList.AddRange(propertyName);
10 
11             DataTable result = new DataTable();
12             if (list.Count > 0)
13             {
14                 PropertyInfo[] propertys = list[0].GetType().GetProperties();
15                 foreach (PropertyInfo pi in propertys)
16                 {
17                     if (propertyNameList.Count == 0)
18                     {
19                         result.Columns.Add(pi.Name);
20 
21                     }
22                     else
23                     {
24                         if (propertyNameList.Contains(pi.Name))
25                             result.Columns.Add(pi.Name);
26 
27                     }
28                 }
29 
30                 for (int i = 0; i < list.Count; i++)
31                 {
32                     ArrayList tempList = new ArrayList();
33                     foreach (PropertyInfo pi in propertys)
34                     {
35                         if (propertyNameList.Count == 0)
36                         {
37                             object obj = pi.GetValue(list[i], null);
38                             tempList.Add(obj);
39                         }
40                         else
41                         {
42                             if (propertyNameList.Contains(pi.Name))
43                             {
44                                 object obj = pi.GetValue(list[i], null);
45                                 tempList.Add(obj);
46                             }
47                         }
48                     }
49                     object[] array = tempList.ToArray();
50                     result.LoadDataRow(array, true);
51                 }
52             }
53             return result;
54         }

 

posted @ 2018-03-30 16:19  Bonnie_W  阅读(157)  评论(0编辑  收藏  举报