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

  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. }

猜你喜欢

转载自blog.csdn.net/shan1774965666/article/details/81626068