DataTable 转换为List 集合

 1 /// <summary>
 2         /// DataTable 转换为List 集合
 3         /// </summary>
 4         /// <typeparam name="TResult">类型</typeparam>
 5         /// <param name="dt">DataTable</param>
 6         /// <returns></returns>
 7         public static List<TResult> ToLists<TResult>(this DataTable dt) where TResult : class, new()
 8         {
 9             //创建一个属性的列表
10             List<PropertyInfo> prlist = new List<PropertyInfo>();
11             //获取TResult的类型实例  反射的入口
12             Type t = typeof(TResult);
13             //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表 
14             Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
15             //创建返回的集合
16             List<TResult> oblist = new List<TResult>();
17 
18             foreach (DataRow row in dt.Rows)
19             {
20                 //创建TResult的实例
21                 TResult ob = new TResult();
22                 //找到对应的数据  并赋值
23                 prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
24                 //放入到返回的集合中.
25                 oblist.Add(ob);
26             }
27             return oblist;
28         }

 

posted @ 2021-08-18 16:59  Ly博客  阅读(1810)  评论(0编辑  收藏  举报