Home > Backend Development > C#.Net Tutorial > How to compare two dictionaries in C#?

How to compare two dictionaries in C#?

王林
Release: 2023-09-14 10:49:02
forward
1169 people have browsed it

如何在 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);
Copy after login

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);
Copy after login

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;
      }
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template