B-Rad
B-Rad

Reputation: 1557

What is wrong with my List<T>.Distinct()?

I have a class MyItems that implements IEqualityComparer and overrides the following methods:

public bool Equals(MyItems item1, MyItems item2)
{
    return (item1.ID == item2.ID && item1.itemName.Equals(item2));
}
public int GetHashCode(MyItems item)
{
    return item.ID.GetHashCode() ^ item.itemName.GetHashCode();
}

First, why is GetHashCode necessary? I understand overriding the Equals method, however, the GetHashCode necessity has eluded me.

Second, this doesn't appear to be working. Is there something I'm doing wrong here? Where I don't understand the GetHashCode, that maybe where I am tripping up.

Upvotes: 3

Views: 172

Answers (3)

gdoron
gdoron

Reputation: 150263

The Distinct method works as follows:

  1. Check if the two objects has the same hash code using GetHashCode.
  2. If they do, now make sure they absolutely equals with Equals.

The GetHashCode is a first check for the more expensive check: Equals

Your Equals method has an error:

return (item1.ID == item2.ID && item1.itemName.Equals(item2));

Should be:

return (item1.ID == item2.ID && item1.itemName.Equals(item2.itemName));
//                                                         ^^^^^^^^^

Also, if the List or the array type you're using isn't of <MyItems> type you also need to override the Equals method.

Upvotes: 6

Alexandar
Alexandar

Reputation: 936

If you want to compare objects you should override Equals(object obj) in their class.

Also, whenever you override Equals(object obj) it is good practice to override GetHashCode

Upvotes: 1

Corey Adler
Corey Adler

Reputation: 16137

To answer your first question, just look here for more information.

To answer your second question: You forgot item2 should be item2.itemName

return (item1.ID == item2.ID && item1.itemName.Equals(item2.itemName));

Upvotes: 8

Related Questions