How to convert a generic set List to a able

Source: Internet
Author: User

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;
}

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.