Data Table Conversion
1 /// <summary> 2 // data table conversion class 3 /// </summary> 4 /// <typeparam name = "T"> </typeparam> 5 public class DbTableConvertor <T> where T: new () 6 {7 // <summary> 8 // convert DataTable to Object List 9 /// </summary> 10 /// <param name = "dt"> to be converted DataTable </param> 11 // <returns> </returns> 12 public List <T> ConvertToList (DataTable dt) 13 {14 // define the set 15 var list = new List <T> (); 16 17 if (0 = dt. rows. count) 18 {19 return lis T; 20} 21 22 // obtain this model's writeable public attribute 23 IEnumerable <System. reflection. propertyInfo> propertys = new T (). getType (). getProperties (). where (u => u. canWrite); 24 list = ConvertToEntity (dt, propertys); 25 26 27 return list; 28} 29 30 // <summary> 31 // convert the first line of the DataTable to the object 32 // </summary> 33 // <param name = "dt"> DataTable to be converted </param> 34 // <returns> </returns> 35 public T ConvertToEntity (DataTable dt) 36 {37 DataTable DtTable = dt. clone (); 38 dtTable. rows. add (dt. rows [0]. itemArray); 39 return ConvertToList (dtTable) [0]; 40} 41 private List <T> ConvertToEntity (DataTable dt, IEnumerable <System. reflection. propertyInfo> propertys) 42 {43 var list = new List <T> (); 44 // traverse all data rows in the DataTable 45 foreach (DataRow dr in dt. rows) 46 {47 var entity = new T (); 48 49 // traverse all attributes of the object 50 foreach (System. reflection. propertyInfo p in propertys) 51 {52 // assign the attribute name to the Temporary Variable 53 string tmpName = p. name; 54 55 // check whether the DataTable contains this column (column Name = Object attribute Name) 56 if (! Dt. columns. contains (tmpName) continue; 57 // value: 58 object value = dr [tmpName]; 59 // if not empty, the property 60 if (value! = DBNull. value) 61 {62 p. setValue (entity, value, null); 63} 64} 65 // Add the object to the 66 list in the generic set. add (entity); 67} 68 return list; 69} 70}View Code