C # convert DataTable to List <T>,
C # convert DataTable to List <T>
When developing a website using a three-tier architecture, you want to convert the DataTable object to a List <T> object, so you can find the information on the Internet and summarize a convenient method to implement it-use reflection.
Ideas:
Overall code:
Reflected property information obtained
The column information in the DataTable. After comparison, we will find that the first letter of the attribute is in upper case, while the column name is in the Camel name, and the first letter is in lower case. However, dt can be found through single-step debugging. columns. contanis (tempName) returns true, which proves that the comparison is case insensitive.
Get T object information
1 // <summary> 2 // use reflection to convert the DataTable to List <T> Object 3 /// </summary> 4 /// <param name = "dt "> DataTable object </param> 5 // <returns> List <T> set </returns> 6 public static List <T> DataTableToList <T> (DataTable dt) where T: class, new () 7 {8 // defines the set 9 List <T> ts = new List <T> (); 10 // define a temporary variable 11 string tempName = string. empty; 12 // traverse all data rows in the DataTable 13 foreach (DataRow dr in dt. rows) 14 {15 T = new t (); 16 // Obtain the public attributes of this model 17 PropertyInfo [] propertys = t. getType (). getProperties (); 18 // traverse all attributes of the Object 19 foreach (PropertyInfo pi in propertys) 20 {21 tempName = pi. name; // assign the attribute Name to the Temporary Variable 22 // check whether the DataTable contains this column (column Name = Object attribute Name) 23 if (dt. columns. contains (tempName) 24 {25 // value 26 object value = dr [tempName]; 27 // if not empty, the property 28 if (value! = DBNull. value) 29 {30 pi. setValue (t, value, null); 31} 32} 33} 34 // Add the object to 35 ts in the generic set. add (t); 36} 37 return ts; 38}View Code