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

时间:2011-08-11 01:53:31

标签: c# .net

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

Dictionary
[
    {key : value}
]

Dictionary1
[
    {key : value2}
]

6 个答案:

答案 0 :(得分:19)

如果您要做的只是查看密钥是否不同但不知道它们是什么,您可以在每个字典的SequenceEqual属性上使用Keys扩展方法:

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);

答案 1 :(得分:1)

return dict1.Count == dict2.Count && 
       dict1.Keys.All(dict2.ContainsKey);

答案 2 :(得分:0)

如果有帮助,您可以获取密钥的集合并将其编入索引。

dictionary1.keys[0] == dictionary2.keys[5]

我实际上不确定你是用数字索引它还是用密钥本身来做它,所以试试这两个。

答案 3 :(得分:0)

试试这个

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;
}

答案 4 :(得分:0)

您可以使用此功能(具体取决于您是否需要相交或排除):

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);

答案 5 :(得分:0)

您可以:

new HashSet<TKey>(dictionary1.Keys).SetEquals(dictionary2.Keys)

请注意,如果dictionary1使用与dictionary2不同的比较器。您必须确定“平等”是否意味着一个或另一个字典认为意味着(或完全不然的其他东西)...