extension Method (1) DataTable and list convert to each other

Source: Internet
Author: User
Tags foreach list of attributes static class

Recently since the company's development environment has changed. From VS2003 to VS2008 after the use of C # 3.0 of new things, their own accumulation of methods slowly more.

Since frequent use of the DataTable is now used list<t> this requires frequent conversion. With more, naturally need to write a simple way to achieve mutual conversion

We can simplify our development with such a feature because of the extension method c#3.0.

The DataTable is converted to list<t> and we can simplify it by extending the DataTable

public static Class DataTableExtensions
{

<summary>
DataTable Conversion to list collection
</summary>
<typeparam name= "TResult" > Type </typeparam>
<param name= "DT" >DataTable</param>
<returns></returns>
public static list<tresult> tolist<tresult> (this DataTable dt) where tresult:class,new ()
{
Create a list of attributes
list<propertyinfo> prlist = new list<propertyinfo> ();
Gets the TResult of the type instance reflected by the
Type t = typeof (TResult);
Get all the public properties of the TResult and find the attributes (PropertyInfo) with the same column name as the TResult property and DataTable and add to the list of properties
Array.foreach<propertyinfo> (T.getproperties (), p => {if (dt. Columns.indexof (P.name)!=-1) prlist. ADD (P); });
Create the returned collection
list<tresult> oblist = new list<tresult> ();

foreach (DataRow row in dt. Rows)
{
To create an instance of TResult
TResult ob = new TResult ();
Find the corresponding data and assign the value
Prlist. ForEach (P => {if (Row[p.name]!= dbnull.value) p.setvalue (ob, row[p.name], NULL);
Into the returned collection.
Oblist. ADD (OB);
}
return oblist;
}
}

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.