C#DataTable去重操作
程序员文章站
2022-06-10 18:31:13
...
#region datatable去重
/// <summary>
/// datatable去重
/// </summary>
/// <param name="dtSource">需要去重的datatable</param>
/// <param name="columnNames">依据哪些列去重</param>
/// <returns></returns>
public static DataTable GetDistinctTable(DataTable dtSource, params string[] columnNames)
{
DataTable distinctTable = dtSource.Clone();
try
{
if (dtSource != null && dtSource.Rows.Count > 0)
{
DataView dv = new DataView(dtSource);
distinctTable = dv.ToTable(true, columnNames);
}
}
catch (Exception e)
{
}
return distinctTable;
}
/// <summary>
/// datatable去重
/// </summary>
/// <param name="dtSource">需要去重的datatable</param>
/// <returns></returns>
public static DataTable GetDistinctTable(DataTable dtSource)
{
DataTable distinctTable = null;
try
{
if (dtSource != null && dtSource.Rows.Count > 0)
{
string[] columnNames = GetTableColumnName(dtSource);
DataView dv = new DataView(dtSource);
distinctTable = dv.ToTable(true, columnNames);
}
}
catch (Exception e)
{
}
return distinctTable;
}
#endregion
#region 获取表中所有列名
public static string[] GetTableColumnName(DataTable dt)
{
string cols = string.Empty;
for (int i = 0; i < dt.Columns.Count; i++)
{
cols += (dt.Columns[i].ColumnName + ",");
}
cols = cols.TrimEnd(',');
return cols.Split(',');
}
#endregion
上一篇: SQL Server判断对象是否存在(整理中...)
下一篇: 用数组实现数据记录的批量录入方法