DataTable to List

Source: Internet
Author: User

From: http://blog.csdn.net/dinglang_2009/article/details/6951138

Using System; using System. collections. generic; using System. linq; using System. text; using System. data; using System. collections; using System. reflection; namespace DatableToList {class ConvertHelper <T> where T: new () {// <summary> /// use reflection and generics /// </summary> /// <param name = "dt"> </param> /// <returns> </returns> public static List <T> ConvertToList (DataTable dt) {// define the set List <T> ts = new List <T> ();// Obtain the Type type = typeof (T) of this model; // define a temporary variable string tempName = string. empty; // traverses all data rows in the DataTable foreach (DataRow dr in dt. rows) {T t = new T (); // obtain the public attributes of this model. PropertyInfo [] propertys = t. getType (). getProperties (); // traverses all attributes of the object. foreach (PropertyInfo pi in propertys) {tempName = pi. name; // assign the attribute Name to the Temporary Variable // check whether the DataTable contains this column (column Name = Object attribute Name) if (dt. columns. contains (tempName) {// determines whether this property has Setter if (! Pi. canWrite) continue; // This attribute cannot be written, jump out directly // value object value = dr [tempName]; // if it is not empty, the property if (value! = DBNull. value) pi. setValue (t, value, null) ;}// Add the object to ts in the generic set. add (t) ;}return ts ;}}}

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.