DataTable轉換List


 1 public class DtToList<T> where T : new()  
 2     {
 3         /// <summary>
 4         /// datatable轉list
 5         /// </summary>
 6         /// <param name="dt"></param>
 7         /// <returns></returns>
 8         public static  List<T> ConvertToModel(DataTable dt)
 9         {
10 
11             List<T> ts = new List<T>();// 定義集合
12             Type type = typeof(T); // 獲得此模型的類型
13             string tempName = "";
14             foreach (DataRow dr in dt.Rows)
15             {
16                 T t = new T();
17                 PropertyInfo[] propertys = t.GetType().GetProperties();// 獲得此模型的公共屬性
18                 foreach (PropertyInfo pi in propertys)
19                 {
20                     tempName = pi.Name;
21                     if (dt.Columns.Contains(tempName))
22                     {
23                         if (!pi.CanWrite) continue;
24                         object value = dr[tempName];
25                         if (value != DBNull.Value)
26                             pi.SetValue(t, value, null);
27                     }
28                 }
29                 ts.Add(t);
30             }
31             return ts;
32         }
33     }
34 
35 datatable轉list
View Code
 1 public class DtToList<T> where T : new()  
 2     {
 3         /// <summary>
 4         /// datatable轉list
 5         /// </summary>
 6         /// <param name="dt"></param>
 7         /// <returns></returns>
 8         public static  List<T> ConvertToModel(DataTable dt)
 9         {
10 
11             List<T> ts = new List<T>();// 定義集合
12             Type type = typeof(T); // 獲得此模型的類型
13             string tempName = "";
14             foreach (DataRow dr in dt.Rows)
15             {
16                 T t = new T();
17                 PropertyInfo[] propertys = t.GetType().GetProperties();// 獲得此模型的公共屬性
18                 foreach (PropertyInfo pi in propertys)
19                 {
20                     tempName = pi.Name;
21                     if (dt.Columns.Contains(tempName))
22                     {
23                         if (!pi.CanWrite) continue;
24                         object value = dr[tempName];
25                         if (value != DBNull.Value)
26                             pi.SetValue(t, value, null);
27                     }
28                 }
29                 ts.Add(t);
30             }
31             return ts;
32         }
33     }
34 
35 datatable轉list
View Code
 
         

 

 

 


免責聲明!

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



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