How do I use HashSet as a dictionary key?

后端 未结 3 594
名媛妹妹
名媛妹妹 2020-12-16 10:51

I wish to use HashSet as the key to a Dictionary:

Dictionary, TValue> myDictionary = new Dictionary

        
相关标签:
3条回答
  • 2020-12-16 10:52

    You can provide a IEqualityComparer<HashSet<T>> to the Dictionary constructor and make the desired implementation in that comparer.

    0 讨论(0)
  • 2020-12-16 10:53

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

    var myDictionary = new Dictionary<HashSet<T>, TValue>(HashSet<T>.CreateSetComparer());
    
    0 讨论(0)
  • 2020-12-16 11:15

    digEmAll's answer is clearly the better choice in practice, since it uses built in code instead of reinventing the wheel. But I'll leave this as a sample implementation.


    You can use implement an IEqualityComparer<HashSet<T>> that uses SetEquals. Then pass it to the constructor of the Dictionary. Something like the following(Didn't test it):

    class HashSetEqualityComparer<T>: IEqualityComparer<HashSet<T>>
    {
        public int GetHashCode(HashSet<T> hashSet)
        {
            if(hashSet == null)
               return 0;
            int h = 0x14345843; //some arbitrary number
            foreach(T elem in hashSet)
            {
                h = unchecked(h + hashSet.Comparer.GetHashCode(elem));
            }
            return h;
        }
    
        public bool Equals(HashSet<T> set1, HashSet<T> set2)
        {
            if(set1 == set2)
                return true;
            if(set1 == null || set2 == null)
                return false;
            return set1.SetEquals(set2);
        }
    }
    

    Note that the hash function here is commutative, that's important because the enumeration order of the elements in the set is undefined.

    One other interesting point is that you can't just use elem.GetHashCode since that will give wrong results when a custom equality comparer was supplied to the set.

    0 讨论(0)
提交回复
热议问题