Home
Map
Dictionary Equals: If Contents Are the SameTest two Dictionary instances for equality of all elements, where ordering does not matter.
C#
This page was last reviewed on Apr 26, 2023.
Dictionary, Equals. Two Dictionaries are equal if their contents are the same. A Dictionary is a reference type—its bits cannot just be checked.
Shows a dictionary
Two Dictionaries may have different orders of keys, even if they are equal. The counts, and exact contents, of the collections must be tested.
Example code. Two Dictionary instances are allocated upon the managed heap at program runtime. Each Dictionary has 3 key-value pairs. The data is equal in every way.
Dictionary
Generic
Info Counts are tested. Every key from the first Dictionary is looked up in the second, and its value is also checked.
Shows a dictionary
using System; using System.Collections.Generic; class Program { static void Main() { // Create a dictionary and add several elements to it. var dict = new Dictionary<string, int>(); dict.Add("cat", 2); dict.Add("dog", 3); dict.Add("x", 4); // Create another dictionary. var dict2 = new Dictionary<string, int>(); dict2.Add("cat", 2); dict2.Add("dog", 3); dict2.Add("x", 4); // Test for equality. bool equal = false; if (dict.Count == dict2.Count) // Require equal count. { equal = true; foreach (var pair in dict) { int value; if (dict2.TryGetValue(pair.Key, out value)) { // Require value be equal. if (value != pair.Value) { equal = false; break; } } else { // Require key be present. equal = false; break; } } } Console.WriteLine(equal); } }
True
Notes, algorithm. The algorithm used has several details. If you do not correctly add every constraint, it will not return correct results. The counts of the 2 dictionaries must be equal.
Info This prevents a larger second dictionary from matching a smaller first. Every key must be found.
Also Values must be equal in both dictionaries. If the key is not found, the match fails.
1. Counts 2. All keys are found 3. All keys have matching values
A summary. It is possible to compare two Dictionary instances for equality using a custom method with key-value pair checking. There are other possible implementations.
However, this implementation is resource-efficient and simple. When testing this method, make sure to change keys and values in both dictionaries.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 26, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.