泛型List集合转化为DateTable

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 
 6 namespace coDEalers
 7 {
 8     public static class Extension
 9     {
10         public static DataTable ListToDataTable<T>(this IList<T> data, string tableName)
11         {
12             DataTable table = new DataTable(tableName);
13 
14             //special handling for value types and string
15             if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
16             {
17 
18                 DataColumn dc = new DataColumn("Value");
19                 table.Columns.Add(dc);
20                 foreach (T item in data)
21                 {
22                     DataRow dr = table.NewRow();
23                     dr[0] = item;
24                     table.Rows.Add(dr);
25                 }
26             }
27             else
28             {
29                 PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
30                 foreach (PropertyDescriptor prop in properties)
31                 {
32                     table.Columns.Add(prop.Name, 
33                     Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
34                 }
35                 foreach (T item in data)
36                 {
37                     DataRow row = table.NewRow();
38                     foreach (PropertyDescriptor prop in properties)
39                     {
40                         try
41                         {
42                             row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
43                         }
44                         catch (Exception ex)
45                         {
46                             row[prop.Name] = DBNull.Value;
47                         }
48                     }
49                     table.Rows.Add(row);
50                 }
51             }
52             return table;
53         }
54     }
55 }

上面的是方法,下面是调用的方法

DataTable dt = null;
List<StateList> stateListObj = JsonConvert.DeserializeObject<List<StateList>>(hdn_stateDetails_JSON.Value);
dt = stateListObj.ListToDataTable<StateList>("dtState");

这是个通用的方法,只要将需要转换的集合传进来就行了

posted @ 2017-10-16 13:16  幼儿园扛把子胜哥  阅读(587)  评论(1)    收藏  举报