C # transforms a DataTable into a list<t>
When using a three-tier architecture to develop a Web site, I want to convert the DataTable object to a List<t> object, and then find the information on the Internet, summarizing a more convenient way to achieve it-using reflection.
Ideas:
- Initializes a List<t> object
- Gets all properties to T, Initializes a T object
- Traverse all attributes, if the value of the corresponding attribute in the DataTable is assigned to the T object, if there is no corresponding column, check if the data model is not defined correctly (property names are not case-sensitive compared to column names)
- To add a T object to a List<t> object
Overall code:
Property information that the reflection gets to
The column information in the DataTable, compared, 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 can be found through single-step debugging dt. The return value of Columns.contanis (Tempname) is true, thus proving that this comparison is case-insensitive
Get to T object information
1 /// <summary> 2 ///Convert a DataTable to a list using reflection<T>Object3 /// </summary> 4 /// <param name= "DT" >DataTable Object</param> 5 /// <returns>List<T>Collection</returns> 6 Public StaticList<t> datatabletolist<t> (DataTable DT)whereT:class,New ()7 { 8 //Defining Collections9list<t> ts =NewList<t>(); Ten //define a temporary variable One stringTempname =string. Empty; A //traverse all data rows in a DataTable - foreach(DataRow Drinchdt. Rows) - { theT t =NewT (); - //get the public properties of this model -propertyinfo[] Propertys =T.gettype (). GetProperties (); - //Traverse All properties of this object + foreach(PropertyInfo Piinchpropertys) - { +Tempname = Pi. Name;//Assigning a property name to a temporary variable A //Check if DataTable contains this column (column name = = Property Name of object) at if(dt. Columns.contains (tempname)) - { - //Take value - ObjectValue =Dr[tempname]; - //if not NULL, the property assigned to the object - if(Value! =DBNull.Value) in { -Pi. SetValue (T,value,NULL); to } + } - } the //object is added to the generic collection * ts. ADD (t); $ } Panax Notoginseng returnts; -}
View Code
C # transforms a DataTable into a list<t>