DatableToList.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. namespace SIMDP.DAL.DalData
  8. {
  9. public class DatableToList
  10. {
  11. public static List<T> ConvertToList<T>(DataTable dt) where T : new()
  12. {
  13. //定义集合
  14. List<T> ts = new List<T>();
  15. //获得此模型的类型
  16. Type type = typeof(T);
  17. //定义一个临时变量
  18. string tempName = string.Empty;
  19. //便利DataTable数据行
  20. foreach (DataRow dr in dt.Rows)
  21. {
  22. T t = new T();
  23. //获得此模型的公共属性
  24. PropertyInfo[] propertys = t.GetType().GetProperties();
  25. //遍历该对象的所有属性
  26. foreach(PropertyInfo pi in propertys)
  27. {
  28. tempName = pi.Name;//将属性名称赋值给临时变量
  29. //检查DataTable是否包含此列(列名==对象的属性名)
  30. if (dt.Columns.Contains(tempName))
  31. {
  32. // 判断此属性是否有Setter
  33. if (!pi.CanWrite) continue;//该属性不可写,直接跳出
  34. //取值
  35. object value = dr[tempName];
  36. //如果非空,则赋给对象的属性
  37. if (value != DBNull.Value)
  38. pi.SetValue(t, value, null);
  39. }
  40. }
  41. //对象添加到泛型集合中
  42. ts.Add(t);
  43. }
  44. return ts;
  45. }
  46. }
  47. }