DataTable与List集合转化

用于数据库查询数据转换、批量数据操作转换、导入导出Excel转换

 1 public static class DataTableHelper
 2 {
 3     /// <summary>
 4     /// 将DataTable对象转换成List对象
 5     /// </summary>
 6     /// <typeparam name="T">元数据类型</typeparam>
 7     /// <param name="table">DataTable类型的对象</param>
 8     /// <returns>返回List对象</returns>
 9     public static IList<T> ConvertTo<T>(DataTable table)
10     {
11         if (table == null)
12             return null;
13 
14         List<DataRow> rows = table.Rows.Cast<DataRow>().ToList();
15 
16         return ConvertTo<T>(rows);
17     }
18 
19     public static IList<T> ConvertTo<T>(IList<DataRow> rows)
20     {
21         IList<T> list = new List<T>();
22         if (rows != null)
23         {
24             foreach (DataRow row in rows.Cast<DataRow>().ToList())
25             {
26                 T obj = default(T);
27                 obj = Activator.CreateInstance<T>();
28                 foreach (DataColumn column in row.Table.Columns)
29                 {
30                     var columnName = column.ColumnName;
31                     var prop = obj.GetType().GetProperty(columnName);
32                     if (prop == null) continue;
33                     var value = (row[columnName] is DBNull) ? null : row[columnName];
34                     if (prop.CanWrite)
35                         prop.SetValue(obj, value, null);
36                 }
37                 list.Add(obj);
38             }
39         }
40         return list;
41     }
42 
43     /// <summary>
44     /// 将IList对象转换成DataTable
45     /// </summary>
46     /// <typeparam name="T">类型</typeparam>
47     /// <param name="list">源数据</param>
48     /// <returns>返回DataTable</returns>
49     public static DataTable ConvertTo<T>(IList<T> list)
50     {
51         DataTable dt = new DataTable();
52         if (list.Count == 0)
53             return dt;
54 
55         //创建table类型
56         var t=Activator.CreateInstance<T>();
57         dt.TableName = typeof(T).Name;
58 
59         PropertyInfo[] props=t.GetType().GetProperties();
60         foreach (PropertyInfo p in props)
61         {
62             string propName = p.Name;
63             Type propType=p.PropertyType;
64 
65             if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
66             {
67                 propType = p.PropertyType.GetGenericArguments()[0];
68             }
69             dt.Columns.Add(propName,propType);
70         }
71 
72         //赋值
73         foreach (var item in list)
74         {
75             DataRow row = dt.NewRow();
76             foreach (PropertyInfo p in props)
77             { 
78                 var propValue=p.GetValue(item,null);
79                 row[p.Name] = propValue;
80             }
81             dt.Rows.Add(row);
82         }
83 
84         return dt;
85     }
86 }

猜你喜欢

转载自www.cnblogs.com/glory0727/p/8973981.html