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