C# 將DataTable數據源轉換成實體類


 1 using System;
 2 using System.Collections.Generic;
 3 using System.Data;
 4 using System.Reflection;
 5 
 6 /// <summary>
 7 /// 將DataTable數據源轉換成實體類
 8 /// </summary>
 9 /// <typeparam name="T">實體</typeparam>
10 public static class ToModel<T> where T : new()
11 {
12     /// <summary>
13     /// 將DataTable數據源轉換成實體類
14     /// </summary>
15     public static List<T> ConvertToModel(DataTable dt)
16     {
17         List<T> ts = new List<T>();// 定義集合
18         foreach (DataRow dr in dt.Rows)
19         {
20             T t = new T();
21             PropertyInfo[] propertys = t.GetType().GetProperties();// 獲得此模型的公共屬性
22             foreach (PropertyInfo pi in propertys)
23             {
24                 if (dt.Columns.Contains(pi.Name))
25                 {
26                     if (!pi.CanWrite) continue;
27                     var value = dr[pi.Name];
28                     if (value != DBNull.Value)
29                     {
30                         switch (pi.PropertyType.FullName)
31                         {
32                             case "System.Decimal":
33                                 pi.SetValue(t, decimal.Parse(value.ToString()), null);
34                                 break;
35                             case "System.String":
36                                 pi.SetValue(t, value.ToString(), null);
37                                 break;
38                             case "System.Int32":
39                                 pi.SetValue(t, int.Parse(value.ToString()), null);
40                                 break;
41                             default:
42                                 pi.SetValue(t, value, null);
43                                 break;
44                         }
45                     }
46                 }
47             }
48             ts.Add(t);
49         }
50         return ts;
51     }
52 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM