//<summary>
///Use reflection to convert a DataTable to a List<t> object
//</summary>
//<param name= "DT" &G T;datatable object </param>
///<returns>List<T> collection </returns>
public static list<t> Datatabletolist<t> (DataTable dt) where t:class,new ()
{
//define collection
list<t> ts = new list<t> () ;
//define a temporary variable
string tempname = string. Empty;
//Traverse all data rows in the DataTable
foreach (DataRow dr in Dt. Rows)
{
T = new T ();
//Get public properties of this model
propertyinfo[] Propertys = T.gettype (). GetProperties ();
//Traverse all properties of the Object
foreach (PropertyInfo pi in propertys)
{
Tempname = pi. name;//assigns the property name to the temporary variable
//checks whether the DataTable contains this column (the column name = = Property name of the object)
if (dt. Columns.contains (tempname))
{
//value
Object value = Dr[tempname];
//If non-null, the property assigned to the object
if (value! = DBNull. Value)
{
Pi. SetValue (t, value, NULL);
}
}
}
//object added to the generic collection
Ts. ADD (t);
}
return ts;
}
Call Method:
list<searchlist> callcostlist = datatabletolist<searchlist> (feetable);
Convert DataTable to List