I have the following datatable – Let’s say called MyTable:
Col1: Col2: Col3: Col4:
1 abc def <null>
2 abc def ghi
1 abc def <null>
3 abc def <null>
1 abc def <null>
And I’m trying to get the distinct rows:
Col1: Col2: Col3: Col4:
1 abc def <null>
2 abc def ghi
3 abc def <null>
I tried the following LINQ statement:
MyTable = (From dr As DataRow In MyTable Select dr).Distinct.CopyToDataTable
But it’s returning the original datatable with the repeated rows back to me.
What am I doing wrong AND how can I get my desired output??
Distinctrelies on the objects all implementingIEquatableand/or having sensible implementations ofGetHashCodeandEquals. TheDataRowclass…doesn’t. It doesn’t check that the value of each column is equal in theEqualsmethod, it just uses the default implementation, which is to say that it checks that the references are equal, and that’s not what you want.You can provide your own
IEqualityComparer, since you can’t change the methods inDataRow.The following should work, if you provide an instance of it to to
Distinct: