How to compare two dictionaries in C#?


To compare two dictionaries, firstly set the two dictionaries −

Dictionary One

IDictionary<int, int> d = new Dictionary<int, int>();
d.Add(1,97);
d.Add(2,89);
d.Add(3,77);
d.Add(4,88);

// Dictionary One elements
Console.WriteLine("Dictionary One elements: "+d.Count);

Dictionary One

IDictionary<int, int> d2 = new Dictionary<int, int>();
d2.Add(1,97);
d2.Add(2,89);
d2.Add(3,77);
d2.Add(4,88);

// Dictionary Two elements
Console.WriteLine("Dictionary Two elements: "+d2.Count);

Now let us compare them −

bool equal = false;
if (d.Count == d2.Count) { // Require equal count.
   equal = true;
   foreach (var pair in d) {
      int value;
      if (d2.TryGetValue(pair.Key, out value)) {
         if (value != pair.Value) {
            equal = false;
            break;
         }
      } else {
         equal = false;
         break;
      }
   }
}

The above compares two dictionaries. Now print console and the result would be True. That would mean both the dictionaries have the same values.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 21-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements