DataTable转为List对象

 1  public static List<T> Convert2Object<T>(DataTable dt) where T : new() 
 2         {
 3             List<T> list = new List<T>();
 4             foreach (DataRow dr in dt.Rows)
 5             {
 6                 list.Add(ToEntity<T>(dr));
 7             }
 8             return list;
 9         }
10 
11         public static T ToEntity<T>(DataRow dr) where T : new()
12         {
13             T model = new T();
14             foreach (PropertyInfo pInfo in model.GetType().GetProperties())
15             {
16                 object val = GetValueByColumnName(dr, pInfo.Name);
17                 pInfo.SetValue(model, val, null);
18             }
19             return model;
20         }
21 
22         private static object GetValueByColumnName(System.Data.DataRow dr, string columnName)
23         {
24             if (dr.Table.Columns.IndexOf(columnName) >= 0)
25             {
26                 if (dr[columnName] == DBNull.Value)
27                     return null;
28                 return dr[columnName];
29             }
30             return null;
31         }

 

posted on 2015-10-03 23:27  symcious  阅读(207)  评论(0编辑  收藏  举报

导航