Generally, we use entity classes in generic projects. However, when we process special data, we must not convert the generics into datatable,
The following is a common method, which is implemented through reflection...
/// <Summary>
/// Convert the List class of the generic set to datatable
/// </Summary>
/// <Param name = "list"> generic type set </param>
/// <Returns> </returns>
Public static datatable listtodatatable <t> (list <t> entitys)
{
// Check whether the object set cannot be empty
If (entitys = NULL | entitys. Count <1)
{
Throw new exception ("the set to be converted is empty ");
}
// Retrieve all properties of the first object
Type entitytype = entitys [0]. GetType ();
Propertyinfo [] entityproperties = entitytype. getproperties ();
// Generate the structure of the datatable
// Cache the generated able structure in the production code.
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 entity to datatable
Foreach (Object entity in entitys)
{
// Check that all objects belong to the same type
If (entity. GetType ()! = Entitytype)
{
Throw new exception ("the element types of the set to be converted are 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;
}