你可以这样做:
你可以这样做:
using System.Linq;
using System.Collections.Generic;
public static class DictionaryExtensions {
public static bool IsEqualTo(this Dictionary<string, Tuple<string, string>> dict1, Dictionary<string, Tuple<string, string>> dict2) {
if (!Enumerable.SequenceEqual(dict1.Keys.OrderBy(x => x), dict2.Keys.OrderBy(x => x))) {
return false;
}
foreach(var kvp in dict1) {
var corresponding = dict2[kvp.Key];
if (kvp.Value.Item1 != corresponding.Item1 || kvp.Value.Item2 != corresponding.Item2) {
return false;
}
}
return true;
}
}
然后使用它:
Dictionary<string, Tuple<string, string>> dict1= new Dictionary<string, Tuple<string, string>>();
Dictionary<string, Tuple<string, string>> dict2= new Dictionary<string, Tuple<string, string>>();
Console.WriteLine(dict1.IsEqualTo(dict2));
dict1["a"] = new Tuple<string, string>("a", "b");
dict2["a"] = new Tuple<string, string>("a", "b");
Console.WriteLine(dict1.IsEqualTo(dict2));
dict2["a"] = new Tuple<string, string>("a", "b2");
Console.WriteLine(dict1.IsEqualTo(dict2));
dict2["a"] = new Tuple<string, string>("a", "b");
dict2["b"] = new Tuple<string, string>("a", "b2");
Console.WriteLine(dict1.IsEqualTo(dict2));
更新 感谢 Aluan Haddad 指出的排序问题。
System.Tuple
类型族不支持==
和!=
运算符重载,这是很不幸的。然而,为了提高性能和易用性,建议您考虑使用System.ValueTuple
类型族,它们支持==
和!=
运算符,并且可以简洁地写成(string, string)
的形式,例如Dictionary<string, (string, string)>
。 - Aluan Haddadfor
/foreach
循环和几个if
语句 就可以开始了吗? - TheGeneral