Remove duplicates from DataTable and custom IEqualityComparer<DataRow>
Posted
by abatishchev
on Stack Overflow
See other posts from Stack Overflow
or by abatishchev
Published on 2009-10-21T08:32:58Z
Indexed on
2010/06/06
15:22 UTC
Read the original article
Hit count: 929
How have I to implement IEqualityComparer<DataRow> to remove duplicates rows from a DataTable with next structure:
ID primary key, col_1, col_2, col_3, col_4
The default comparer doesn't work because each row has it's own, unique primary key.
How to implement IEqualityComparer<DataRow> that will skip primary key and compare only data remained.
I have something like this:
public class DataRowComparer : IEqualityComparer<DataRow>
{
public bool Equals(DataRow x, DataRow y)
{
return
x.ItemArray.Except(new object[] { x[x.Table.PrimaryKey[0].ColumnName] }) ==
y.ItemArray.Except(new object[] { y[y.Table.PrimaryKey[0].ColumnName] });
}
public int GetHashCode(DataRow obj)
{
return obj.ToString().GetHashCode();
}
}
and
public static DataTable RemoveDuplicates(this DataTable table)
{
return
(table.Rows.Count > 0) ?
table.AsEnumerable().Distinct(new DataRowComparer()).CopyToDataTable() :
table;
}
but it calls only GetHashCode() and doesn't call Equals()
© Stack Overflow or respective owner