Public classConverthelper<t>whereT:New() { /// <summary> ///take advantage of reflection and generics/// </summary> /// <param name= "DT" ></param> /// <returns></returns> Public StaticList<t>converttolist (DataTable dt) {//Defining Collectionslist<t> ts =NewList<t>(); //get the type of this modelType type =typeof(T); //define a temporary variable stringTempname =string. Empty; //traverse all data rows in a DataTable foreach(DataRow Drinchdt. Rows) {T T=NewT (); //get the public properties of this modelpropertyinfo[] Propertys =T.gettype (). GetProperties (); //Traverse All properties of this object foreach(PropertyInfo Piinchpropertys) {Tempname= Pi. Name;//Assigning a property name to a temporary variable//Check if DataTable contains this column (column name = = Property Name of object) if(dt. Columns.contains (Tempname)) {//determine if this property has a setter if(!pi. CanWrite)Continue;//This property is not writable and jumps directly out of//Take value ObjectValue =Dr[tempname]; //if not NULL, the property assigned to the object if(Value! =dbnull.value) pi. SetValue (t, value,NULL); } } //object is added to the generic collectionts. ADD (t); } returnts; } Public StaticT converttom (DataTable dt) {//get the type of this modelType type =typeof(T); //define a temporary variable stringTempname =string. Empty; //traverse all data rows in a DataTableDataRow dr = dt. rows[0]; T T=NewT (); //get the public properties of this modelpropertyinfo[] Propertys =T.gettype (). GetProperties (); //Traverse All properties of this object foreach(PropertyInfo Piinchpropertys) {Tempname= Pi. Name;//Assigning a property name to a temporary variable//Check if DataTable contains this column (column name = = Property Name of object) if(dt. Columns.contains (Tempname)) {//determine if this property has a setter if(!pi. CanWrite)Continue;//This property is not writable and jumps directly out of//Take value ObjectValue =Dr[tempname]; //if not NULL, the property assigned to the object if(Value! =dbnull.value) pi. SetValue (t, value,NULL); } } returnT; } }
View Code
Underwear: DataTable to model