<summary>
Convert a generic type collection List class to a DataTable
</summary>
<param name= "list" > generic type Collection </param>
<returns></returns>
public static DataTable listtodatatable<t> (list<t> entitys)
{
Check entity collection cannot be empty
if (Entitys = = NULL | | entitys. Count < 1)
{
throw new Exception ("the set to be converted is empty");
}
Remove all Propertie from the first entity
Type EntityType = entitys[0]. GetType ();
propertyinfo[] entityproperties = Entitytype.getproperties ();
Generate a structure for a DataTable
In the production code, the resulting datatable structure should be cache, slightly
DataTable dt = new DataTable ();
for (int i = 0; i < entityproperties.length; i++)
{
Dt. Columns.Add (Entityproperties[i]. Name, Entityproperties[i]. PropertyType);
Dt. Columns.Add (Entityproperties[i]. Name);
}
Add all of the entity to the DataTable
foreach (object entity in Entitys)
{
Check that all entities are of the same type
if (entity. GetType ()! = EntityType)
{
throw new Exception ("The collection element type to be converted is inconsistent");
}
object[] entityvalues = new Object[entityproperties.length];
for (int i = 0; i < entityproperties.length; i++)
{
Entityvalues[i] = entityproperties[i]. GetValue (entity, NULL);
}
Dt. Rows.Add (entityvalues);
}
return DT;
}
Converting a list collection class to a DataTable