使用C#,我想比较两个字典是特定的,两个字典具有相同的键但不是相同的值,我找到了一个方法Comparer但我不太确定如何使用它?除了遍历每个键之外还有其他方法吗?
Dictionary
[
{key : value}
]
Dictionary1
[
{key : value2}
]
Run Code Online (Sandbox Code Playgroud)
vcs*_*nes 20
如果您只想查看键是否不同但不知道它们是什么,则可以SequenceEqual在Keys每个字典的属性上使用扩展方法:
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)
小智 5
return dict1.Count == dict2.Count &&
dict1.Keys.All(dict2.ContainsKey);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13580 次 |
| 最近记录: |