我可以比较两个词典的键吗?

moi*_*ega 11 .net c#

使用C#,我想比较两个字典是特定的,两个字典具有相同的键但不是相同的值,我找到了一个方法Comparer但我不太确定如何使用它?除了遍历每个键之外还有其他方法吗?

Dictionary
[
    {key : value}
]

Dictionary1
[
    {key : value2}
]
Run Code Online (Sandbox Code Playgroud)

vcs*_*nes 20

如果您只想查看键是否不同但不知道它们是什么,则可以SequenceEqualKeys每个字典的属性上使用扩展方法:

Dictionary<string,string> dictionary1;
Dictionary<string,string> dictionary2;
var same = dictionary1.Count == dictionary2.Count && dictionary1.Keys.SequenceEqual(dictionary2.Keys);
Run Code Online (Sandbox Code Playgroud)

如果你想要实际差异,可以这样:

var keysDictionary1HasThat2DoesNot = dictionary1.Keys.Except(dictionary2.Keys);
var keysDictionary2HasThat1DoesNot = dictionary2.Keys.Except(dictionary1.Keys);
Run Code Online (Sandbox Code Playgroud)

  • a)Count比较是多余的,因为SequenceEqual就是这样.b)SequenceEqual不能与Dictionary一起使用,因为它要求键的顺序相同.它可能在某些情况下有效,但如果添加和删除了密钥,则会失败. (2认同)

小智 5

return dict1.Count == dict2.Count && 
       dict1.Keys.All(dict2.ContainsKey);
Run Code Online (Sandbox Code Playgroud)