/// <summary> /// DataTable转成List /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dt"></param> /// <returns></returns> public static List<T> GetTableToList<T>(this DataTable dt) { var list = new List<T>(); var plist = new List<PropertyInfo>(typeof(T).GetProperties()); foreach (DataRow item in dt.Rows) { T s = Activator.CreateInstance<T>(); for (int i = 0; i < dt.Columns.Count; i++) { PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName); if (info != null) { try { if (!Convert.IsDBNull(item[i])) { object v = null; if (info.PropertyType.ToString().Contains("System.Nullable")) { v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType)); } else { v = Convert.ChangeType(item[i], info.PropertyType); } info.SetValue(s, v, null); } } catch (Exception ex) { throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message); } } } list.Add(s); } return list; } /// <summary> /// List集合转DataTable /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="list">传入集合</param> /// <returns>返回datatable结果</returns> public static DataTable GetListToTable<T>(List<T> list) { Type tp = typeof(T); PropertyInfo[] proInfos = tp.GetProperties(); DataTable dt = new DataTable(); foreach (var item in proInfos) { dt.Columns.Add(item.Name, item.PropertyType); //添加列名及对应类型 } foreach (var item in list) { DataRow dr = dt.NewRow(); foreach (var proInfo in proInfos) { object obj = proInfo.GetValue(item); if (obj == null) { continue; } dr[proInfo.Name] = obj; } dt.Rows.Add(dr); } return dt; }