DataTableExtension.cs 1.5 KB

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