c#拓展方法将datatable转换成实体

69 篇文章 1 订阅
63 篇文章 0 订阅
  1. /// <summary>
  2. /// DataTable 转换为 List<T>
  3. /// </summary>
  4. /// <typeparam name="T"></typeparam>
  5. /// <param name="dt"></param>
  6. /// <returns></returns>
  7. public static List<T> ToList<T>(this DataTable dt) where T : class,new()
  8. {
  9. Type t = typeof(T);
  10. PropertyInfo[] propertys = t.GetProperties();
  11. List<T> lst = new List<T>();
  12. string typeName = string.Empty;
  13.  
  14. foreach (DataRow dr in dt.Rows)
  15. {
  16. T entity = new T();
  17. foreach (PropertyInfo pi in propertys)
  18. {
  19. typeName = pi.Name;
  20. if (dt.Columns.Contains(typeName))
  21. {
  22. if (!pi.CanWrite) continue;
  23. object value = dr[typeName];
  24. if (value == DBNull.Value) continue;
  25. if (pi.PropertyType == typeof(string))
  26. {
  27. pi.SetValue(entity, value.ToString(), null);
  28. }
  29. else if (pi.PropertyType == typeof(int) || pi.PropertyType == typeof(int?))
  30. {
  31. pi.SetValue(entity, int.Parse(value.ToString()), null);
  32. }
  33. else if (pi.PropertyType == typeof(DateTime?) || pi.PropertyType == typeof(DateTime))
  34. {
  35. pi.SetValue(entity, DateTime.Parse(value.ToString()), null);
  36. }
  37. else if (pi.PropertyType == typeof(float) || pi.PropertyType == typeof(float?))
  38. {
  39. pi.SetValue(entity, float.Parse(value.ToString()), null);
  40. }
  41. else if (pi.PropertyType == typeof(double) || pi.PropertyType == typeof(double?))
  42. {
  43. pi.SetValue(entity, double.Parse(value.ToString()), null);
  44. }
  45. else if (pi.PropertyType == typeof(byte) || pi.PropertyType == typeof(byte?))
  46. {
  47. pi.SetValue(entity, byte.Parse(value.ToString()), null);
  48. }
  49. else if (pi.PropertyType == typeof(Int16) || pi.PropertyType == typeof(Int16?))
  50. {
  51. pi.SetValue(entity, Int16.Parse(value.ToString()), null);
  52. }
  53. else
  54. {
  55. pi.SetValue(entity, value, null);
  56. }
  57. }
  58. }
  59. lst.Add(entity);
  60. }
  61. return lst;
  62. }

// 调用:List<User> userList = TableToEntity<User>(YourDataTable);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值