将DataTable转成List集合的方法

 

 1 public static List<T> TableToListModel<T>(DataTable dt) where T : new()
 2         {
 3             List<T> res = new List<T>();
 4             // 获得此模型的类型   
 5             Type type = typeof(T);
 6             string tempName = "";
 7             foreach (DataRow dr in dt.Rows)
 8             {
 9                 T t = new();
10                 // 获得此模型的公共属性      
11                 PropertyInfo[] propertys = t.GetType().GetProperties();
12                 foreach (PropertyInfo pi in propertys)
13                 {
14                     //针对特性的
15                     if (pi.CustomAttributes.FirstOrDefault() != null)
16                         tempName = pi.CustomAttributes.FirstOrDefault().NamedArguments.FirstOrDefault().TypedValue.Value.ToString();
17                     else
18                         tempName = pi.Name;// 检查DataTable是否包含此列  .Name;
19                     if (dt.Columns.Contains(tempName))
20                     {
21                         // 判断此属性是否有Setter      
22                         if (!pi.CanWrite) continue;
23                         object value = dr[tempName];
24                         if (value != DBNull.Value)
25                             pi.SetValue(t, value, null);
26                     }
27                 }
28                 res.Add(t);
29             }
30             return res;
31         }

 

posted @ 2022-05-10 16:47  进击的黑大帅  阅读(771)  评论(0)    收藏  举报