Convert DataTable to List

Source: Internet
Author: User

//<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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.