You can extend the DataTable to simplify the DataTable conversion to List <T>.
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;
}
}
On the contrary, you also need to convert List <T> to DataTable. We can implement this by extending IEnumberable <T>.
/// <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;
}
}
The code above shows that reflection is mainly implemented through reflection. The reflection efficiency seems to be a little slow, but it is acceptable ..
Of course, you can also use the expression tree to dynamically construct Lambda expressions to improve efficiency ..
Extension Method (1) DataTable and List Mutual Conversion