Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for equality between dictionaries in C#

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())); } 
like image 956
rony l Avatar asked Sep 27 '10 13:09

rony l


People also ask

How do you know if two dictionaries are equal?

Use == operator to check if the dictionaries are equal It will return True the dictionaries are equals and False if not.

Can we compare two dictionaries in C#?

No... actually keys must be same in name and count.

Are dictionaries equal C#?

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.


1 Answers

dic1.Count == dic2.Count && !dic1.Except(dic2).Any(); 
like image 164
Nick Jones Avatar answered Oct 08 '22 05:10

Nick Jones