C# DataTable 转实体集合 List<T>

 1 public class ModelConvertHelper<T> where T : new()  // 此处一定要加上new()
 2         {
 3  
 4             public static IList<T> ConvertToModel(DataTable dt)
 5             {
 6  
 7                 IList<T> ts = new List<T>();// 定义集合
 8                 Type type = typeof(T); // 获得此模型的类型
 9                 string tempName = "";
10                 foreach (DataRow dr in dt.Rows)
11                 {
12                     T t = new T();
13                     System.Reflection.PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
14                     foreach (System.Reflection.PropertyInfo pi in propertys)
15                     {
16                         tempName = pi.Name;
17                         if (dt.Columns.Contains(tempName))
18                         {
19                             if (!pi.CanWrite) continue;
20                             object value = dr[tempName];
21                             if (value != DBNull.Value)
22                                 pi.SetValue(t, value, null);
23                         }
24                     }
25                     ts.Add(t);
26                 }
27                 return ts;
28             }
29         }

 

posted @ 2020-05-21 15:17  Vaynedy  阅读(451)  评论(0编辑  收藏  举报