3

I would like to use HashSet<> in order to store large quantities (50-100) of a certain custom class, lets call it "Poster." As far as I know there is some performance benefit in using HashSet<> for large number of items over List<>. But in order to take advantage of this performance gain, do I "need" to define both of these?

  • public bool Equals(Poster a, Poster b)
  • public int GetHashCode(Poster obj)

UPDATE: For anyone looking on how to implement these, this is how I've done it:

public bool Equals(PosterImage a, PosterImage b)
{
    return (a.ApiId == b.ApiId);
}

public int GetHashCode(PosterImage obj)
{
    return ((PosterImage) obj).ApiId.GetHashCode();
}
IKnowledge
  • 221
  • 3
  • 12
  • possible duplicate of [How does HashSet compare elements for equality](http://stackoverflow.com/questions/8952003/how-does-hashset-compare-elements-for-equality) – BartoszKP Nov 03 '14 at 17:46
  • What kind of performance benefit are you hoping to get? Checking for the existance of an item in a hash set is a lot faster than in a list, but for anything else it would rather be slightly slower. – Guffa Nov 03 '14 at 17:51
  • This will be used in quite a few places, I was hoping to return HashSet from the data-layer to be used by many other methods, just looking for the most efficient method on average. – IKnowledge Nov 03 '14 at 17:53

1 Answers1

5

Yes, if you implement a IEqualityComparer<Poster>, you need to implement these methods. You will need to pass the equality comparer to the HashSet<Poster> constructor.

Another option is to implement the equality/hashcode logic in the Poster class itself; in this case you must override these methods:

public bool Equals(object obj)
public int GetHashCode()
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758