码迷,mamicode.com
首页 > 其他好文 > 详细

DataTable转为List对象

时间:2015-10-04 00:24:00      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

 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         }

 

DataTable转为List对象

标签:

原文地址:http://www.cnblogs.com/symcious/p/4854012.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!