DataTable與List集合轉化
阿新 • • 發佈:2018-04-30
return cast typedef for sum init style create ==
用於數據庫查詢數據轉換、批量數據操作轉換、導入導出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 19public 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 }
DataTable與List集合轉化