找出两个字典之间的差异



我有下面的代码比较两个字典。在字典中,可以是具有不同或相同值的多个键。如果两个字典完全相同,则返回true。如果有什么不同(例如……在dict1中不存在键,但在dict2中存在,或者相同键的值不同- false。因此,这段代码的问题是,如果我添加到dict1,反之亦然,我添加新的KeyValuePair,或者键没有排序来比较它们,它将不会正确返回方法。基本上我需要正确比较两个字典它们可以是键和值完全不同的,也可以是相同的。在两个字典中,KeyValuePairs的顺序也可以不同。

public static bool FlagsAreEqual(Dictionary<string, string> currentEntity, Dictionary<string, string> changedEntity)
{
var equals = false;
foreach (KeyValuePair<string, string> kvp in currentEntity)
{
if (changedEntity.Contains(kvp))
{
equals = true;
}
else
{
equals = false;
}
}
return equals;
}
public static void Main()
{
var dicOne = new Dictionary<string, string>() { { "asdf", "asdf" }, { "few", "faew" } };
var dicTwo = new Dictionary<string, string>() { { "asdf", "asdf" }, { "few", "aaa" } };
if (!FlagsAreEqual(dicOne, dicTwo))
{
Console.WriteLine("update");
}
else
{
Console.WriteLine("not update");
}
Console.ReadKey();
}

我建议这样做:

using System.Linq;
...
public static bool FlagsAreEqual<K, V>(Dictionary<K, V> currentEntity, 
Dictionary<K, V> changedEntity) {
// currentEntity and changedEntity share the same reference
if (ReferenceEquals(currentEntity, changedEntity))
return true;
// one of dictionaries (but not both - since ReferenceEquals is not true) is null
if (currentEntity is null || changedEntity is null)
return false;
// there are added / removed keys
if (currentEntity.Keys.Count != changedEntity.Key.Count)
return false;
// finally, each currentEntity key has corresponding changedEntity one
// with equal value
return currentEntity.All(pair =>
changedEntity.TryGetValue(pair.Key, out var value) && Equals(value, pair.Value));
}

最新更新