/// <summary> /// list转datatable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collection"></param> /// <returns></returns> public static DataTable ListToDataTable<T>(IEnumerable<T> collection) { var props = typeof(T).GetProperties(); var dt = new DataTable(); dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray()); if (collection.Count() > 0) { for (int i = 0; i < collection.Count(); i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in props) { object obj = pi.GetValue(collection.ElementAt(i), null); tempList.Add(obj); } object[] array = tempList.ToArray(); dt.LoadDataRow(array, true); } } return dt; } /// <summary> /// datatable转list /// </summary> /// <param name="dt"></param> /// <returns></returns> public static List<T> DataTableToList<T>(DataTable dt) where T : new() { List<T> ts = new List<T>();// 定义集合 Type type = typeof(T); // 获得此模型的类型 string tempName = ""; foreach (DataRow dr in dt.Rows) { T t = new T(); PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性 foreach (PropertyInfo pi in propertys) { tempName = pi.Name; if (dt.Columns.Contains(tempName)) { if (!pi.CanWrite) continue; object value = dr[tempName]; if (value != DBNull.Value) { if(pi.PropertyType == typeof(decimal)) pi.SetValue(t, decimal.Parse(value.ToString()), null); else if (pi.PropertyType == typeof(double)) pi.SetValue(t, double.Parse(value.ToString()), null); else if (pi.PropertyType == typeof(float)) pi.SetValue(t, float.Parse(value.ToString()), null); else if (pi.PropertyType == typeof(int)) pi.SetValue(t, int.Parse(value.ToString()), null); else if (pi.PropertyType == typeof(DateTime)) pi.SetValue(t, DateTime.Parse(value.ToString()), null); else pi.SetValue(t, value, null); } } } ts.Add(t); } return ts; }
标签:pi,list,value,转化,typeof,new,dt,null,datatable From: https://www.cnblogs.com/itjeff/p/18682577