I wish to use HashSet<T>
as the key to a Dictionary:
Dictionary<HashSet<T>, TValue> myDictionary = new Dictionary<HashSet<T>, TValue>();
I want to look up values from the dictionary such that two different instances of HashSet<T>
that contain the same items will return the same value.
HashSet<T>
's implementations of Equals()
and GetHashCode()
don't seem to do this (I think they're just the defaults). I can override Equals()
to use SetEquals()
but what about GetHashCode()
? I feel like I am missing something here...
A HashSet, similar to a Dictionary, is a hash-based collection, so look ups are very fast with O(1). But unlike a dictionary, it doesn't store key/value pairs; it only stores values. So, every objects should be unique and this is determined by the value returned from the GetHashCode method.
A HashSet<T> object's capacity automatically increases as elements are added to the object. A HashSet<T> collection is not sorted and cannot contain duplicate elements. HashSet<T> provides many mathematical set operations, such as set addition (unions) and set subtraction.
-1 Dictionary does NOT use GetHashCode() to determine if two keys are equal. That is, a dictionary can contain separate entries whose keys have the same hash code. The dictionary may be less efficient, but it will still work.
You could use the set comparer provided by HashSet<T>
:
var myDictionary = new Dictionary<HashSet<T>, TValue>(HashSet<T>.CreateSetComparer());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With