Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. LINQ;
Using system. text;
Using system. reflection;
Public static class datatableextensions
{
/// <Summary>
/// Datatable is converted to a list set
/// </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> ();
// Obtain the entry for reflection of tresult-type instances
Type T = typeof (tresult );
// Obtain all the public attributes of tresult, find the attributes with the same tresult attribute and datatable column name (propertyinfo), and add them to the attribute list
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)
{
// Create a tresult instance
Tresult Ob = new tresult ();
// Locate the corresponding data and assign a value
Prlist. foreach (P => {If (row [P. Name]! = Dbnull. Value) p. setvalue (OB, row [P. name], null );});
// Put it into the returned collection.
Oblist. Add (OB );
}
Return oblist;
}
/// <Summary>
/// Convert to a able
/// </Summary>
/// <Typeparam name = "tresult"> </typeparam>
///// <Param name = "value"> </param>
/// <Returns> </returns>
Public static datatable todatatable <tresult> (this ienumerable <tresult> value) Where tresult: Class
{
// Create a set of attributes
List <propertyinfo> plist = new list <propertyinfo> ();
// Obtain the reflection entry
Type type = typeof (tresult );
Datatable dt = new datatable ();
// Add all public attributes to the set and add datatable Columns
Array. foreach <propertyinfo> (type. getproperties (), P => {plist. add (p); DT. columns. add (P. name, P. propertytype );});
Foreach (VAR item in value)
{
// Create a datarow instance
Datarow ROW = DT. newrow ();
// Assign a value to the row
Plist. foreach (P => row [P. Name] = P. getvalue (item, null ));
// Add to datatable
DT. Rows. Add (ROW );
}
Return DT;
}
}