Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I compare the keys of two dictionaries?

Tags:

c#

.net

Using C#, I want to compare two dictionaries to be specific, two dictionaries with the same keys but not same values, I found a method Comparer but I'm not quite sure how can I use it? Is there a way other than iterating through each key?

Dictionary
[
    {key : value}
]

Dictionary1
[
    {key : value2}
]
like image 453
moisesvega Avatar asked Aug 11 '11 01:08

moisesvega


People also ask

Can we compare 2 dictionaries in Python?

Using == operator to Compare Two Dictionaries Here we are using the equality comparison operator in Python to compare two dictionaries whether both have the same key value pairs or not.

Can two dictionaries be compared?

The easiest way (and one of the more robust at that) to do a deep comparison of two dictionaries is to serialize them in JSON format, sorting the keys, and compare the string results: import json if json.

How do you check if two dictionaries have the same keys and values?

Check if two nested dictionaries are equal in Python To do this task, we are going to use the == operator and this method will help the user to check whether the two given dictionaries are equal or not.


2 Answers

If all you want to do is see if the keys are different but not know what they are, you can use the SequenceEqual extension method on the Keys property of each dictionary:

Dictionary<string,string> dictionary1;
Dictionary<string,string> dictionary2;
var same = dictionary1.Count == dictionary2.Count && dictionary1.Keys.SequenceEqual(dictionary2.Keys);

If you want the actual differences, something like this:

var keysDictionary1HasThat2DoesNot = dictionary1.Keys.Except(dictionary2.Keys);
var keysDictionary2HasThat1DoesNot = dictionary2.Keys.Except(dictionary1.Keys);
like image 120
vcsjones Avatar answered Oct 13 '22 14:10

vcsjones


return dict1.Count == dict2.Count && 
       dict1.Keys.All(dict2.ContainsKey);
like image 21
Андрей Ивойлов Avatar answered Oct 13 '22 12:10

Андрей Ивойлов