Dictionary.ContainsKey 当 Key 是另一个字典时

Dictionary.ContainsKey When Key is Another Dictionary

我正在尝试回答这个 leetcode 问题:

https://leetcode.com/problems/group-anagrams/

我知道这是 hashmap 问题,我选择执行如下操作:

IList<IList<string>> GroupAnagrams(string[] strs)
{
    Dictionary<SortedDictionary<char, int>, List<string>> history = new Dictionary<SortedDictionary<char, int>, List<string>>();
    foreach (string phrase in strs)
    {
        SortedDictionary<char, int> signature = new SortedDictionary<char, int>();
        foreach (char c in phrase.ToCharArray())
        {
            if (signature.ContainsKey(c))
            {
                signature[c] += 1;
            }
            else
            {
                signature.Add(c, 1);
            }
        }
        if (history.ContainsKey(signature))
        {
            history[signature].Add(phrase);
        }
        else
        {
            history[signature] = new List<string>();
            history[signature].Add(phrase);
        }
    }

    IList<IList<string>> result = new List<IList<string>>();
    foreach (var pair in history)
    {
        result.Add(pair.Value);
    }

    return list;
}

想法是签名是字符计数器。如果两个短语具有相同的签名,那么它们就是一个变位词。但是,我注意到在通过调试器单步执行代码时,方法调用 history.ContainsKey(signature) 永远不会 returns 为真。即使在跨迭代监视调试器中的局部变量时也是如此。我想知道这是不是因为签名应该是一个 SortedDictionary,但这似乎没有效果。事实上,当我查看当地人的历史时,它似乎有重复的钥匙。谁能解释一下这是怎么回事?

Can anyone explain what's going on?

字典(和排序字典)不是按值比较,而是按引用相等进行比较。 ContainsKey 将 return 为真的唯一方法是字典中是否存在作为其参数传递的实际对象。

换句话说,这段代码打印了两次“false”:

Console.WriteLine(new Dictionary<char, int>() == new Dictionary<char, int>());
Console.WriteLine(new Dictionary<char, int> { 'a', 1 } == new Dictionary<char, int> { 'a', 1 });