Trying to find unique rows in a data table using Distinct() extension method. Some rows contain exactly the same data, but for some reason, the hash code for these rows are different from each other.
I wrote a comparer class implementing IEqualityComparer<DataRow>, however, I think what I’m doing in GetHashCode() is cheesy and nasty.
The reason I’ve done it this way is because Equals() never gets called unless the hashcodes are the same (Expected behaviour)
class RowValidationComparer : IEqualityComparer<DataRow>
{
public bool Equals(DataRow x, DataRow y)
{
return x.Field<string>("MyField").Equals(y.Field<string>("MyField"));
}
public int GetHashCode(DataRow obj)
{
typeof(DataRow).GetHashCode();
}
}
To do this, you can use the DataRowComparer class:
For a general explanation from MSDN, discussing the use of set operators such as Distinct on DataRows: