You would think that if two dictionaries contained the same keys and values they would return the same hash code and be equal right? but they don’t – what am i doing wrong? or how do I compare dictionaries in this way?
Thanks. Code sameple below
/In this case I also want to test the order is the same/equal.
SortedDictionary<int,string> sd1 = new SortedDictionary<int,string>();
sd1.Add(1,"one");
sd1.Add(2, "two");
sd1.Add(5, "five");
int sd1Hash = sd1.GetHashCode();
SortedDictionary<int, string> sd2 = new SortedDictionary<int, string>();
sd2.Add(1, "one");
sd2.Add(2, "two");
sd2.Add(5, "five");
int sd2Hash = sd2.GetHashCode();
//This is false
bool areEqual = sd1.Equals(sd2);
If you want to test that the collections are equal, including their ordering:
If you wanted to treat the collections as unordered sets:
(
SequenceEqualandIntersectcan also take anIEqualityComparerparameter, if required.)As several other answers have stated,
SortedDictionarydoesn’t override the default implementations ofEqualsorGetHashCode. The default implementation ofEqualswill use reference equality and returnfalsebecause you’re comparing two separate objects.