123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- using Logs;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace cuidian.Sql
- {
- public class DataTableUtils
- {
- /// <summary>
- /// 根据列标题获得列名
- /// </summary>
- /// <param name="dt"></param>
- /// <param name="desc"></param>
- /// <returns></returns>
- public static string GetColumnName(DataTable dt, string desc)
- {
- Dictionary<string, string> maps = GetColumnMaps(dt);
- if (maps.ContainsKey(desc)) return maps[desc];
- LogHelper.Debug("未在表中找到列" + desc);
- throw new Exception("未在表中找到列" + desc);
- }
- /// <summary>
- /// 获得列名,列标题映射表
- /// </summary>
- /// <param name="dt"></param>
- /// <returns></returns>
- public static Dictionary<string, string> GetColumnMaps(DataTable dt)
- {
- Dictionary<string, string> maps = new Dictionary<string, string>();
- foreach (DataColumn item in dt.Columns)
- {
- maps.Add(item.Caption, item.ColumnName);
- }
- return maps;
- }
- /// <summary>
- /// 获得指定DataTable,指定列的唯一数据
- /// </summary>
- /// <param name="dt"></param>
- /// <param name="col"></param>
- /// <returns></returns>
- public static List<string> GetDistinctValue(DataTable dt, string col)
- {
- List<string> values = new List<string>();
- DataView dataView = dt.DefaultView;
- DataTable dataTableDistinct = dataView.ToTable(true, col);
- dataTableDistinct.Columns[0].ColumnName = "code";
- foreach (DataRow item in dataTableDistinct.Rows)
- {
- values.Add(item[0].ToString());
- }
- return values;
- }
- public static List<string> DataTableToList(DataTable dt)
- {
- return DataTableToList(dt, dt.Columns[0].ColumnName);
- }
- public static List<string> DataTableToList(DataTable dt, string col)
- {
- List<string> values = new List<string>();
- foreach (DataRow dr in dt.Rows)
- {
- values.Add(dr[col].ToString());
- }
- return values;
- }
- public static string GetColData(DataRow dr, string col)
- {
- string data = string.Empty;
- try
- {
- object o = dr[col];
- if (o != null) data = o.ToString();
- }
- catch (Exception ex)
- {
- LogHelper.Debug("获取字段" + col + "失败", ex);
- throw ex;
- }
- return data;
- }
- }
- }
|