d2=newDic"/> d2=newDic">

Home  >  Article  >  Backend Development  >  How to compare two dictionaries in C#?

How to compare two dictionaries in C#?

王林
王林forward
2023-09-14 10:49:021155browse

如何在 C# 中比较两个字典?

To compare two dictionaries, first set up 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 Let's 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;
      }
   }
}

Two dictionaries are compared above. Now print the console and the result will be True. This means both dictionaries have the same value.

The above is the detailed content of How to compare two dictionaries in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete