
1 public class DtToList<T> where T : new() 2 { 3 /// <summary> 4 /// datatable转list 5 /// </summary> 6 /// <param name="dt"></param> 7 /// <returns></returns> 8 public static List<T> ConvertToModel(DataTable dt) 9 { 10 11 List<T> ts = new List<T>();// 定义集合 12 Type type = typeof(T); // 获得此模型的类型 13 string tempName = ""; 14 foreach (DataRow dr in dt.Rows) 15 { 16 T t = new T(); 17 PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性 18 foreach (PropertyInfo pi in propertys) 19 { 20 tempName = pi.Name; 21 if (dt.Columns.Contains(tempName)) 22 { 23 if (!pi.CanWrite) continue; 24 object value = dr[tempName]; 25 if (value != DBNull.Value) 26 pi.SetValue(t, value, null); 27 } 28 } 29 ts.Add(t); 30 } 31 return ts; 32 } 33 } 34 35 datatable转list

1 public class DtToList<T> where T : new() 2 { 3 /// <summary> 4 /// datatable转list 5 /// </summary> 6 /// <param name="dt"></param> 7 /// <returns></returns> 8 public static List<T> ConvertToModel(DataTable dt) 9 { 10 11 List<T> ts = new List<T>();// 定义集合 12 Type type = typeof(T); // 获得此模型的类型 13 string tempName = ""; 14 foreach (DataRow dr in dt.Rows) 15 { 16 T t = new T(); 17 PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性 18 foreach (PropertyInfo pi in propertys) 19 { 20 tempName = pi.Name; 21 if (dt.Columns.Contains(tempName)) 22 { 23 if (!pi.CanWrite) continue; 24 object value = dr[tempName]; 25 if (value != DBNull.Value) 26 pi.SetValue(t, value, null); 27 } 28 } 29 ts.Add(t); 30 } 31 return ts; 32 } 33 } 34 35 datatable转list