Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use HashSet<T> as a dictionary key?

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...

like image 446
GraemeF Avatar asked May 06 '11 10:05

GraemeF


People also ask

Is HashSet same as dictionary?

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.

How does a HashSet work c#?

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.

Does dictionary use Hashcode?

-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.


1 Answers

You could use the set comparer provided by HashSet<T>:

var myDictionary = new Dictionary<HashSet<T>, TValue>(HashSet<T>.CreateSetComparer()); 
like image 113
digEmAll Avatar answered Sep 20 '22 06:09

digEmAll