DataTableUtils.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using Logs;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace cuidian.Sql
  9. {
  10. public class DataTableUtils
  11. {
  12. /// <summary>
  13. /// 根据列标题获得列名
  14. /// </summary>
  15. /// <param name="dt"></param>
  16. /// <param name="desc"></param>
  17. /// <returns></returns>
  18. public static string GetColumnName(DataTable dt, string desc)
  19. {
  20. Dictionary<string, string> maps = GetColumnMaps(dt);
  21. if (maps.ContainsKey(desc)) return maps[desc];
  22. LogHelper.Debug("未在表中找到列" + desc);
  23. throw new Exception("未在表中找到列" + desc);
  24. }
  25. /// <summary>
  26. /// 获得列名,列标题映射表
  27. /// </summary>
  28. /// <param name="dt"></param>
  29. /// <returns></returns>
  30. public static Dictionary<string, string> GetColumnMaps(DataTable dt)
  31. {
  32. Dictionary<string, string> maps = new Dictionary<string, string>();
  33. foreach (DataColumn item in dt.Columns)
  34. {
  35. maps.Add(item.Caption, item.ColumnName);
  36. }
  37. return maps;
  38. }
  39. /// <summary>
  40. /// 获得指定DataTable,指定列的唯一数据
  41. /// </summary>
  42. /// <param name="dt"></param>
  43. /// <param name="col"></param>
  44. /// <returns></returns>
  45. public static List<string> GetDistinctValue(DataTable dt, string col)
  46. {
  47. List<string> values = new List<string>();
  48. DataView dataView = dt.DefaultView;
  49. DataTable dataTableDistinct = dataView.ToTable(true, col);
  50. dataTableDistinct.Columns[0].ColumnName = "code";
  51. foreach (DataRow item in dataTableDistinct.Rows)
  52. {
  53. values.Add(item[0].ToString());
  54. }
  55. return values;
  56. }
  57. public static List<string> DataTableToList(DataTable dt)
  58. {
  59. return DataTableToList(dt, dt.Columns[0].ColumnName);
  60. }
  61. public static List<string> DataTableToList(DataTable dt, string col)
  62. {
  63. List<string> values = new List<string>();
  64. foreach (DataRow dr in dt.Rows)
  65. {
  66. values.Add(dr[col].ToString());
  67. }
  68. return values;
  69. }
  70. public static string GetColData(DataRow dr, string col)
  71. {
  72. string data = string.Empty;
  73. try
  74. {
  75. object o = dr[col];
  76. if (o != null) data = o.ToString();
  77. }
  78. catch (Exception ex)
  79. {
  80. LogHelper.Debug("获取字段" + col + "失败", ex);
  81. throw ex;
  82. }
  83. return data;
  84. }
  85. }
  86. }