Converting a list collection class to a DataTable

Source: Internet
Author: User

<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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.