我可以比较两本字典的键吗?
本文关键字:字典 两本 比较 我可以 | 更新日期: 2023-09-27 18:05:27
使用c#,我想比较两个字典是具体的,两个字典具有相同的键,但不相同的值,我发现了一个方法比较,但我不太确定我如何使用它?除了遍历每个键,还有别的方法吗?
Dictionary
[
{key : value}
]
Dictionary1
[
{key : value2}
]
如果你想做的只是看看键是否不同,但不知道它们是什么,你可以在每个字典的Keys
属性上使用SequenceEqual
扩展方法:
Dictionary<string,string> dictionary1;
Dictionary<string,string> dictionary2;
var same = dictionary1.Count == dictionary2.Count && dictionary1.Keys.SequenceEqual(dictionary2.Keys);
如果您想要实际的差异,像这样:
var keysDictionary1HasThat2DoesNot = dictionary1.Keys.Except(dictionary2.Keys);
var keysDictionary2HasThat1DoesNot = dictionary2.Keys.Except(dictionary1.Keys);
return dict1.Count == dict2.Count &&
dict1.Keys.All(dict2.ContainsKey);
试试这个
public bool SameKeys<TKey, TValue>(IDictionary<TKey, TValue> one, IDictionary<TKey, TValue> two)
{
if (one.Count != two.Count)
return false;
foreach (var key in one.Keys)
{
if (!two.ContainsKey(key))
return false;
}
return true;
}
如果有帮助的话,您可以获取键的集合并对其进行索引。
dictionary1.keys[0] == dictionary2.keys[5]
我不确定是用数字索引还是用键本身索引,所以两种都试试
你可以这样做(取决于你是想要相交还是排除):
Dictionary<int, int> dict1 = new Dictionary<int, int>();
Dictionary<int, int> dict2 = new Dictionary<int, int>();
IEnumerable<int> keys1ExceptKeys2 = dict1.Keys.Except(dict2.Keys);
IEnumerable<int> keys2ExceptKeys1 = dict2.Keys.Except(dict1.Keys);
IEnumerable<int> keysIntersect = dict1.Keys.Intersect(dict2.Keys);
你可以:
new HashSet<TKey>(dictionary1.Keys).SetEquals(dictionary2.Keys)
如果dictionary1
与dictionary2
使用不同的比较器,请注意。你必须决定"equal"的意思是否和某本或另一本字典认为的一样(或者完全是别的意思)…
我认为这是除计数外检查键之间差异的最快方法。
var isTrue = !dict1.Keys.Any(k => !dict2.Keys.Contains(k)) &&
!dict2.Keys.Any(k => !dict1.Keys.Contains(k));