Assuming dictionary keys and values have their equals and hash methods implemented correctly, what is the most succinct and efficient way to test for equality of two dictionaries?
In this context, two dictionaries are said to be equal if they contain the same set of keys (order not important), and for every such key, they agree on the value.
Here are some ways I came up with (there are probably many more):
public bool Compare1<TKey, TValue>( Dictionary<TKey, TValue> dic1, Dictionary<TKey,TValue> dic2) { return dic1.OrderBy(x => x.Key). SequenceEqual(dic2.OrderBy(x => x.Key)); } public bool Compare2<TKey, TValue>( Dictionary<TKey, TValue> dic1, Dictionary<TKey, TValue> dic2) { return (dic1.Count == dic2.Count && dic1.Intersect(dic2).Count(). Equals(dic1.Count)); } public bool Compare3<TKey, TValue>( Dictionary<TKey, TValue> dic1, Dictionary<TKey, TValue> dic2) { return (dic1.Intersect(dic2).Count(). Equals(dic1.Union(dic2).Count())); }
Use == operator to check if the dictionaries are equal It will return True the dictionaries are equals and False if not.
No... actually keys must be same in name and count.
C# Dictionary Equals: If Contents Are the SameTest two Dictionary instances for equality of all elements, where ordering does not matter. Dictionary, Equals. Two Dictionaries are equal if their contents are the same. A Dictionary is a reference type—its bits cannot just be checked.
dic1.Count == dic2.Count && !dic1.Except(dic2).Any();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With