/// <summary> ///DataTable Goto List<T> /// </summary> Public Static classTabletolist<t>whereT:New() { Public StaticList<t>converttolist (DataTable dt) {List<T> list =NewList<t>(); //get the type of this modelType type =typeof(T); stringtemp =string. Empty; foreach(DataRow Drinchdt. Rows) {T T=NewT (); Propertyinfo[] Propertys= T.gettype (). GetProperties ();//Reflection foreach(PropertyInfo Piinchpropertys) {Temp= 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 (temp)) {//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[temp]; //if not NULL, the property assigned to the object if(Value! =dbnull.value) pi. SetValue (t, value,NULL); } } //object is added to the generic collectionlist. ADD (t); } returnlist; } }
Call the:tabletolist< object;. Converttolist (DT);
DataTable Turn List<t>