Data Table Conversion

Source: Internet
Author: User

Data Table Conversion
1 /// <summary> 2 // data table conversion class 3 /// </summary> 4 /// <typeparam name = "T"> </typeparam> 5 public class DbTableConvertor <T> where T: new () 6 {7 // <summary> 8 // convert DataTable to Object List 9 /// </summary> 10 /// <param name = "dt"> to be converted DataTable </param> 11 // <returns> </returns> 12 public List <T> ConvertToList (DataTable dt) 13 {14 // define the set 15 var list = new List <T> (); 16 17 if (0 = dt. rows. count) 18 {19 return lis T; 20} 21 22 // obtain this model's writeable public attribute 23 IEnumerable <System. reflection. propertyInfo> propertys = new T (). getType (). getProperties (). where (u => u. canWrite); 24 list = ConvertToEntity (dt, propertys); 25 26 27 return list; 28} 29 30 // <summary> 31 // convert the first line of the DataTable to the object 32 // </summary> 33 // <param name = "dt"> DataTable to be converted </param> 34 // <returns> </returns> 35 public T ConvertToEntity (DataTable dt) 36 {37 DataTable DtTable = dt. clone (); 38 dtTable. rows. add (dt. rows [0]. itemArray); 39 return ConvertToList (dtTable) [0]; 40} 41 private List <T> ConvertToEntity (DataTable dt, IEnumerable <System. reflection. propertyInfo> propertys) 42 {43 var list = new List <T> (); 44 // traverse all data rows in the DataTable 45 foreach (DataRow dr in dt. rows) 46 {47 var entity = new T (); 48 49 // traverse all attributes of the object 50 foreach (System. reflection. propertyInfo p in propertys) 51 {52 // assign the attribute name to the Temporary Variable 53 string tmpName = p. name; 54 55 // check whether the DataTable contains this column (column Name = Object attribute Name) 56 if (! Dt. columns. contains (tmpName) continue; 57 // value: 58 object value = dr [tmpName]; 59 // if not empty, the property 60 if (value! = DBNull. value) 61 {62 p. setValue (entity, value, null); 63} 64} 65 // Add the object to the 66 list in the generic set. add (entity); 67} 68 return list; 69} 70}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.