Http://hi.baidu.com/blueyund/blog/item/e1d108f7dc51cb2b720eec9b.html
/// <Summary>
/// Convert a collection class to a able
/// </Summary>
/// <Param name = "list"> set </param>
/// <Returns> </returns>
Public static datatable todatatable (ilist List)
{
Datatable result = new datatable ();
If (list. Count> 0)
{
Propertyinfo [] propertys = list [0]. GetType (). getproperties ();
Foreach (propertyinfo PI in propertys)
{
Result. Columns. Add (PI. Name, Pi. propertytype );
}
For (INT I = 0; I <list. Count; I ++)
{
Arraylist templist = new arraylist ();
Foreach (propertyinfo PI in propertys)
{
Object OBJ = pi. getvalue (list [I], null );
Templist. Add (OBJ );
}
Object [] array = templist. toarray ();
Result. loaddatarow (array, true );
}
}
Return result;
}
/// <Summary>
/// Convert a generic collection class to a able
/// </Summary>
/// <Typeparam name = "T"> set item type </typeparam>
/// <Param name = "list"> set </param>
/// <Returns> dataset (table) </returns>
Public static datatable todatatable <t> (ilist <t> List)
{
Return convertx. todatatable <t> (list, null );
}
/// <Summary>
/// Convert a generic collection class to a able
/// </Summary>
/// <Typeparam name = "T"> set item type </typeparam>
/// <Param name = "list"> set </param>
/// <Param name = "propertyname"> name of the column to be returned </param>
/// <Returns> dataset (table) </returns>
Public static datatable todatatable <t> (ilist <t> list, Params string [] propertyname)
{
List <string> propertynamelist = new list <string> ();
If (propertyname! = NULL)
Propertynamelist. addrange (propertyname );
Datatable result = new datatable ();
If (list. Count> 0)
{
Propertyinfo [] propertys = list [0]. GetType (). getproperties ();
Foreach (propertyinfo PI in propertys)
{
If (propertynamelist. Count = 0)
{
Result. Columns. Add (PI. Name, Pi. propertytype );
}
Else
{
If (propertynamelist. Contains (PI. Name ))
Result. Columns. Add (PI. Name, Pi. propertytype );
}
}
For (INT I = 0; I <list. Count; I ++)
{
Arraylist templist = new arraylist ();
Foreach (propertyinfo PI in propertys)
{
If (propertynamelist. Count = 0)
{
Object OBJ = pi. getvalue (list [I], null );
Templist. Add (OBJ );
}
Else
{
If (propertynamelist. Contains (PI. Name ))
{
Object OBJ = pi. getvalue (list [I], null );
Templist. Add (OBJ );
}
}
}
Object [] array = templist. toarray ();
Result. loaddatarow (array, true );
}
}
Return result;
}