我有一个字典,希望编写一个方法来检查该字典中的所有值是否相同。
字典类型:
Dictionary<string, List<string>>
在我的情况下,{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;
[1,2,3]
和[1,2,3,3]
是相同的吗? - spender