C # convert DataTable to List & lt; T & gt ;,

Source: Internet
Author: User

C # convert DataTable to List <T>,

C # convert DataTable to List <T>

When developing a website using a three-tier architecture, you want to convert the DataTable object to a List <T> object, so you can find the information on the Internet and summarize a convenient method to implement it-use reflection.

Ideas:

Overall code:

Reflected property information obtained

The column information in the DataTable. After comparison, we will find that the first letter of the attribute is in upper case, while the column name is in the Camel name, and the first letter is in lower case. However, dt can be found through single-step debugging. columns. contanis (tempName) returns true, which proves that the comparison is case insensitive.

Get T object information

1 // <summary> 2 // use reflection to convert the DataTable to List <T> Object 3 /// </summary> 4 /// <param name = "dt "> DataTable object </param> 5 // <returns> List <T> set </returns> 6 public static List <T> DataTableToList <T> (DataTable dt) where T: class, new () 7 {8 // defines the set 9 List <T> ts = new List <T> (); 10 // define a temporary variable 11 string tempName = string. empty; 12 // traverse all data rows in the DataTable 13 foreach (DataRow dr in dt. rows) 14 {15 T = new t (); 16 // Obtain the public attributes of this model 17 PropertyInfo [] propertys = t. getType (). getProperties (); 18 // traverse all attributes of the Object 19 foreach (PropertyInfo pi in propertys) 20 {21 tempName = pi. name; // assign the attribute Name to the Temporary Variable 22 // check whether the DataTable contains this column (column Name = Object attribute Name) 23 if (dt. columns. contains (tempName) 24 {25 // value 26 object value = dr [tempName]; 27 // if not empty, the property 28 if (value! = DBNull. value) 29 {30 pi. setValue (t, value, null); 31} 32} 33} 34 // Add the object to 35 ts in the generic set. add (t); 36} 37 return ts; 38}View Code

 

 

 

Related Article

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.