C#.NET – 从DataTable中移除重复记录





4.00/5 (1投票)
一个函数,用于在C#.NET中移除并选择DataTable中的唯一记录,并返回一个干净且无重复记录的DataTable。
引言
如果数据库表包含重复记录,那么使用 DISTINCT 函数很容易选择唯一记录,但是当一个 .NET DataTable 包含重复记录时,就没有内置函数来移除或选择 DataTable
中的唯一记录。
目标
本文的主要目标是创建一个函数,从 C#.NET 中的 DataTable
中移除并选择唯一记录,并返回一个干净且无重复记录的 DataTable
。
解释
为了移除 DataTable
中的重复记录,我创建了以下函数,它需要两个参数:DataTable
和列名。该函数在 DataTable
中搜索重复记录,根据第二个参数提供的列名,并将行(记录)添加到 ArrayList
变量中。然后,通过循环遍历找到的重复记录,从 datatable
中删除记录。
包含重复记录的DataTable
从DataTable中移除重复记录的函数
/// <summary>
/// Remove duplicate records from data table
/// </summary>
/// <param name="table">DataTable for removing duplicate records</param>
/// <param name="DistinctColumn">Column to check for duplicate values or records</param>
/// <returns></returns>
public DataTable RemoveDuplicateRows(DataTable table, string DistinctColumn)
{
try
{
ArrayList UniqueRecords = new ArrayList();
ArrayList DuplicateRecords = new ArrayList();
// Check if records is already added to UniqueRecords otherwise,
// Add the records to DuplicateRecords
foreach(DataRow dRow in table.Rows)
{
if (UniqueRecords.Contains(dRow[DistinctColumn]))
DuplicateRecords.Add(dRow);
else
UniqueRecords.Add(dRow[DistinctColumn]);
}
// Remove duplicate rows from DataTable added to DuplicateRecords
foreach (DataRow dRow in DuplicateRecords)
{
table.Rows.Remove(dRow);
}
// Return the clean DataTable which contains unique records.
return table;
}
catch (Exception ex)
{
return null;
}
}
使用该函数
使用此函数非常简单,您只需要将 datatable
和列名参数传递给该函数,该函数将返回清理后的 datatable
。
示例
DataTable DuplicateRecords = objDatabase.getTable("SQL Query");
DataTable UniqueRecords = RemoveDuplicateRows
(DuplicateRecords, "Column Name to check for duplicate records");
使用上述函数得到的干净且无重复记录的 DataTable
备注
上述函数选择第一个记录,并在 DataTable
中找到重复记录时删除其他记录。
结论
通过使用此函数,您可以清理DataTable中的重复记录。
欢迎评论、建议或提供反馈。