测试字典是否具有相同的值(但可能是不同的键)
public static Boolean DictionaryHaveEqualValues(IDictionary left, IDictionary right) {
if (Object.ReferenceEquals(left, right))
return true;
else if (Object.ReferenceEquals(left, null))
return false;
else if (Object.ReferenceEquals(right, null))
return false;
if (left.Count != right.Count)
return false;
Dictionary<Object, int> reversed = new Dictionary<Object, int>();
foreach (var value in left.Values)
if (reversed.ContainsKey(value))
reversed[value] = reversed[value] + 1;
else
reversed.Add(value, 1);
foreach (var value in right.Values)
if (!reversed.ContainsKey(value))
return false;
else if (reversed[value] == 1)
reversed.Remove(value);
else
reversed[value] = reversed[value] - 1;
return (reversed.Count == 0);
}
....
Dictionary<int, String> main = new Dictionary<int, String>() {
{1, "A"},
{2, "B"},
{3, "A"}
};
Dictionary<int, String> test1 = new Dictionary<int, String>() {
{7, "A"},
{4, "B"},
{5, "A"}
};
Dictionary<int, String> test2 = new Dictionary<int, String>() {
{7, "A"},
{4, "B"},
{5, "A"},
{9, "B"}
};
Dictionary<int, String> test3 = new Dictionary<int, String>() {
{7, "A"},
{4, "C"},
{5, "A"},
};
// Dictionarys have equal values: two "A" and one "B"
Debug.Assert(DictionaryHaveEqualValues(main, test1));
// Unequal: test2 simply has move values
Debug.Assert(!DictionaryHaveEqualValues(main, test2));
// Unequal: test3 doesn't have "B" value
Debug.Assert(!DictionaryHaveEqualValues(main, test3));