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

本文介绍了一种将DataTable转换为List<T>的方法,并提供了具体的C#实现代码。该方法通过反射机制设置对象属性,支持多种数据类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值