DTList.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. using System.Threading.Tasks;
  8. namespace DAL
  9. {
  10. /// <summary>
  11. /// 雷怡 2021-08-17
  12. /// TableData List 互转
  13. /// </summary>
  14. public static class DTList
  15. {
  16. /// <summary>
  17. /// DataTable转换成List<T>
  18. /// </summary>
  19. /// <typeparam name="T"></typeparam>
  20. /// <param name="table"></param>
  21. /// <returns></returns>
  22. public static List<T> ConvertToList<T>(DataTable table)
  23. {
  24. List<T> list = new List<T>();
  25. T t = default(T);
  26. PropertyInfo[] propertypes = null;
  27. string tempName = string.Empty;
  28. foreach (DataRow row in table.Rows)
  29. {
  30. t = Activator.CreateInstance<T>();
  31. propertypes = t.GetType().GetProperties();
  32. foreach (PropertyInfo pro in propertypes)
  33. {
  34. tempName = pro.Name;
  35. if (table.Columns.Contains(tempName))
  36. {
  37. object value = row[tempName];
  38. if (!value.ToString().Equals(""))
  39. {
  40. pro.SetValue(t, value, null);
  41. }
  42. }
  43. }
  44. list.Add(t);
  45. }
  46. return list.Count == 0 ? null : list;
  47. }
  48. /// <summary>
  49. /// List<T>转换成DataTable
  50. /// </summary>
  51. /// <typeparam name="T"></typeparam>
  52. /// <param name="list">实例化当前list<T> 的list集合</param>
  53. /// <param name="dataList">集合数据</param>
  54. /// <returns>返回DataTable</returns>
  55. public static System.Data.DataTable ToDataTable<T>(this System.Collections.Generic.IList<T> list, System.Collections.Generic.IList<T> dataList) where T : class, new()
  56. {
  57. if (dataList == null || !dataList.Any())
  58. {
  59. return null;
  60. }
  61. Type type = typeof(T);
  62. System.Data.DataTable dt = new System.Data.DataTable(type.Name);
  63. System.Reflection.PropertyInfo[] propertyInfoArray = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
  64. foreach (T t in dataList.Where(t => t != null))
  65. {
  66. System.Data.DataRow row = dt.NewRow();
  67. for (int i = 0, j = propertyInfoArray.Length; i < j; i++)
  68. {
  69. System.Reflection.PropertyInfo propertyInfo = propertyInfoArray[i];
  70. string name = propertyInfo.Name;
  71. if (dt.Columns[name] == null)
  72. {
  73. System.Data.DataColumn column = new System.Data.DataColumn(name, propertyInfo.PropertyType);
  74. dt.Columns.Add(column);
  75. }
  76. row[name] = propertyInfo.GetValue(t, null);
  77. }
  78. dt.Rows.Add(row);
  79. }
  80. return dt;
  81. }
  82. }
  83. }