DataTable转List
代码:
1 public class ModelConverHelper<T> where T : new() 2 { 3 public static List<T> ConvertToModelList(DataTable dt) 4 { 5 List<T> ts = new List<T>(); 6 Type type = typeof(T); 7 string tempName = ""; 8 foreach (DataRow dr in dt.Rows) 9 { 10 T t = new T(); 11 PropertyInfo[] propertys = t.GetType().GetProperties(); 12 foreach (PropertyInfo pi in propertys) 13 { 14 tempName = pi.Name;//检查DataTable中是否含有此列 15 if (dt.Columns.Contains(tempName)) 16 { 17 //判断此属性是否有Setter 18 if (!pi.CanWrite) continue; 19 object value = dr[tempName]; 20 if (value != DBNull.Value) 21 { 22 object _o = new object(); 23 var _type = pi.PropertyType; 24 if (_type == typeof(String)) 25 { 26 _o = value.ToString(); 27 } 28 else if (_type == typeof(Int16)) 29 { 30 _o = Convert.ToInt16(value); 31 } 32 else if (_type == typeof(Int32)) 33 { 34 _o = Convert.ToInt32(value); 35 } 36 else if (_type == typeof(Int64)) 37 { 38 _o = Convert.ToInt64(value); 39 } 40 else if (_type == typeof(Double)) 41 { 42 _o = Convert.ToDouble(value); 43 } 44 else if (_type == typeof(Boolean)) 45 { 46 _o = Convert.ToBoolean(value); 47 } 48 else if (_type == typeof(Decimal)) 49 { 50 _o = Convert.ToDecimal(value); 51 } 52 else if (_type == typeof(DateTime)) 53 { 54 _o = Convert.ToDateTime(value); 55 } 56 else 57 { 58 _o = value; 59 } 60 pi.SetValue(t, _o, null); 61 } 62 } 63 } 64 ts.Add(t); 65 } 66 return ts; 67 } 68 }
使用方法:
1 string strSql = "select * from table"; 2 DataSet ds = iDb.GetDataSet(strSql); 3 List<ARCHSJRECORDINFO> list = new List<ARCHSJRECORDINFO>(); 4 list = ModelConverHelper<ARCHSJRECORDINFO>.ConvertToModelList(ds.Tables[0]);