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
{
///
/// 根据列标题获得列名
///
///
///
///
public static string GetColumnName(DataTable dt, string desc)
{
Dictionary maps = GetColumnMaps(dt);
if (maps.ContainsKey(desc)) return maps[desc];
LogHelper.Debug("未在表中找到列" + desc);
throw new Exception("未在表中找到列" + desc);
}
///
/// 获得列名,列标题映射表
///
///
///
public static Dictionary GetColumnMaps(DataTable dt)
{
Dictionary maps = new Dictionary();
foreach (DataColumn item in dt.Columns)
{
maps.Add(item.Caption, item.ColumnName);
}
return maps;
}
///
/// 获得指定DataTable,指定列的唯一数据
///
///
///
///
public static List GetDistinctValue(DataTable dt, string col)
{
List values = new List();
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 DataTableToList(DataTable dt)
{
return DataTableToList(dt, dt.Columns[0].ColumnName);
}
public static List DataTableToList(DataTable dt, string col)
{
List values = new List();
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;
}
}
}