DataTable to object class conversion

Source: Internet
Author: User

Almost everyone in the software knows that DataTable to object class conversion is often used. Commonly used is to assign values to objects using column names or indexed columns. If the number of columns is small, the number of columns is large, it's really annoying and prone to errors. it is also often plagued. this method has long been written. I have never had time. I was busy a few days ago. I have adapted some other methods by referring to some materials. I will share the following:

1. DataTable to List <T> Conversion

Public static List <T> DataTableToT <T> (DataTable source) where T: class, new ()
{
List <T> itemlist = null;
If (source = null | source. Rows. Count = 0)
{
Return itemlist;
}
Itemlist = new List <T> ();
T item = null;
Type targettype = typeof (T );
Type ptype = null;
Object value = null;
Foreach (DataRow dr in source. Rows)
{
Item = new T ();
Foreach (PropertyInfo pi in targettype. GetProperties ())
{
If (pi. CanWrite & source. Columns. Contains (pi. Name ))
{
Ptype = Type. GetType (pi. PropertyType. FullName );
Value = Convert. ChangeType (dr [pi. Name], ptype );
Pi. SetValue (item, value, null );
}
}
Itemlist. Add (item );
}

Return itemlist;
}
2. Conversion from DataRow to T

Public static T DataRowToT <T> (DataRow source) where T: class, new ()
{
T item = null;
If (source = null)
{
Return item;
}
Item = new T ();
Type targettype = typeof (T );
Type ptype = null;
Object value = null;

Foreach (PropertyInfo pi in targettype. GetProperties ())
{
If (pi. CanWrite & source. Table. Columns. Contains (pi. Name ))
{
Ptype = Type. GetType (pi. PropertyType. FullName );
Value = Convert. ChangeType (source [pi. Name], ptype );
Pi. SetValue (item, value, null );
}
}
Return item;
}

Note: 1. Reflection and generics are used in it, and they are both the most basic level.

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.