如何检查字典中的所有值在C#中是否相同?

Viv*_*ain 2 c# dictionary

我有一个字典,我想写一个方法来检查这个字典中的所有值是否相同.字典类型:

Dictionary<string, List<string>>
Run Code Online (Sandbox Code Playgroud)

在我的案例中,列表{1,2,3}和{2,1,3}是相同的.

我之前已经为简单的数据类型值做了这个,但我找不到新要求的逻辑,请帮助我.对于简单值:MyDict.GroupBy(x => x.Value).Where(x => x.Count()> 1)

我还编写了一个通用方法来以这种方式比较两种数据类型.

// 1
            // Require that the counts are equal
            if (a.Count != b.Count)
            {
                return false;
            }
            // 2
            // Initialize new Dictionary of the type
            Dictionary<T, int> d = new Dictionary<T, int>();
            // 3
            // Add each key's frequency from collection A to the Dictionary
            foreach (T item in a)
            {
                int c;
                if (d.TryGetValue(item, out c))
                {
                    d[item] = c + 1;
                }
                else
                {
                    d.Add(item, 1);
                }
            }
            // 4
            // Add each key's frequency from collection B to the Dictionary
            // Return early if we detect a mismatch
            foreach (T item in b)
            {
                int c;
                if (d.TryGetValue(item, out c))
                {
                    if (c == 0)
                    {
                        return false;
                    }
                    else
                    {
                        d[item] = c - 1;
                    }
                }
                else
                {
                    // Not in dictionary
                    return false;
                }
            }
            // 5
            // Verify that all frequencies are zero
            foreach (int v in d.Values)
            {
                if (v != 0)
                {
                    return false;
                }
            }
            // 6
            // We know the collections are equal
            return true;
Run Code Online (Sandbox Code Playgroud)

Sel*_*enç 6

实施IEqualityComparerList<string>该比较基于其内容两个列表.然后,只需使用DistinctValues和检查计数:

dictionary.Values.Distinct(new ListEqualityComparer()).Count() == 1
Run Code Online (Sandbox Code Playgroud)

  • 我冒昧地在答案中提供了比较器的实现. (2认同)