我如何使用的HashSet< T>作为字典键?如何使用、字典、LT、HashSet

2023-09-04 23:41:54 作者:惊觉

我希望用的HashSet< T> 为重点,以一个词典:

I wish to use HashSet<T> as the key to a Dictionary:

Dictionary<HashSet<T>, TValue> myDictionary = new Dictionary<HashSet<T>, TValue>();

我要查找值从字典中的 HashSet的&LT这样两个不同的实例; T&GT; 的的包含相同的项目的将返回相同的值。

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&LT; T&GT; 的实施等于() GetHash code()似乎并没有做到这一点(我认为他们只是默认值)。我可以覆盖等于()使用 SetEquals()但对于 GetHash code()?我觉得我失去了一些东西在这里...

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

推荐答案

您可以使用所提供的一组比较器的HashSet&LT; T&GT;

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

var myDictionary = new Dictionary<HashSet<T>, TValue>(HashSet<T>.CreateSetComparer());