How to remove duplicate rows in a C# datatable?
In C#, you can use the following method to remove duplicate rows in a DataTable:
- Utilize the Distinct method:
DataTable distinctTable = dataTable.AsEnumerable().Distinct(DataRowComparer.Default).CopyToDataTable();
- Query using LINQ:
DataTable distinctTable = dataTable
.AsEnumerable()
.GroupBy(row => new { Col1 = row["Column1"], Col2 = row["Column2"], ... }) // 根据多个列进行分组
.Select(group => group.First()) // 选择每个分组的第一行
.CopyToDataTable();
Please note that the above method can only remove completely identical rows. If you want to remove duplicates based on specific columns, you can specify the columns to be grouped in the GroupBy method.