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;
}
}