![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements