When you use a three-tier architecture to develop a Web site, you want to convert a DataTable object to a List<t> object, and then find data on the web to summarize a more convenient way to implement it-using reflection.
Ideas:
Initializes a List<t> object that gets all the properties of T, Initializes a T object to traverse all the properties, and assigns a value to the T object if the datatable contains the corresponding property. If there are no columns, check that the data model is incorrectly defined (case-insensitive when comparing property names to column names) add a T object to the List<t> object
Overall code:
Property information obtained by reflection
Column information in a DataTable, in contrast to the above figure, we will find that the first letter in the attribute is uppercase, and the column name is the camel named, the first letter is lowercase, but with single-step debugging can be found dt. The return value of Columns.contanis (Tempname) is true, which proves that this comparison is case-insensitive
Get to T object information
<summary>///convert DataTable to list<t> object using reflection///</summary>///<param name= "DT" >da Tatable Objects </param>///<returns>List<T> collections </returns> public static list<t> Datatabl
Etolist<t> (DataTable dt) where t:class,new () {//definition set list<t> ts = new list<t> (); Defines a temporary variable string tempname = String.
Empty; Traverses all data rows in the DataTable foreach (DataRow dr in Dt.
Rows) {T t = new t (); Gets the public properties of this model propertyinfo[] Propertys = T.gettype ().
GetProperties (); Traverses all properties of the object foreach (PropertyInfo pi in propertys) {tempname = pi. name;//assign a property name to a temporary variable//check that the DataTable contains the column (column name = = object's property name) if (DT).
Columns.contains (Tempname)) {//Fetch value Object value = Dr[tempname]; If Non-null, the property of the object is assigned the if (value!= dbnull.value) {pI.setvalue (T,value,null); }}//object added to generic collection TS.
ADD (t);
} return TS; }