I have two dictionaries containing a string key and then an object. The object contains five fields. Is there an elegant way to ensure both dictionaries first contain the same keys and then if this is correct, contain the same five fields per object?
Would the two dictionaries have the same in-built hashcode or something?
EDIT, doesn’t appear to be working for the following code:
Dictionary<string, MyClass> test1 = new Dictionary<string, MyClass>();
Dictionary<string, MyClass> test2 = new Dictionary<string, MyClass>();
MyClass i = new MyClass("", "", 1, 1, 1, 1);
MyClass j = new MyClass("", "", 1, 1, 1, 1);
test1.Add("1", i);
test2.Add("1", j);
bool equal = test1.OrderBy(r => r.Key).SequenceEqual(test2.OrderBy(r => r.Key));
class MyClass
{
private string a;
private string b;
private long? c;
private decimal d;
private decimal e;
private decimal f;
public MyClass(string aa, string bb, long? cc, decimal dd, decimal ee, decimal ff)
{
a= aa;
b= bb;
c= cc;
d= dd;
e= ee;
f= ff;
}
this returns false?
First you have to override
EqualsandGetHashCodemethod in your class, otherwise comparison will be performed on references instead of actual values. (The code to overrideEqualsandGetHashCodeis provided at the end), after that you can use:Since the order in which items in Dictionary are returned is undefined, you can not rely on Dictionary.SequenceEqual (without
OrderBy).You can try:
Most of the time the above will return
true, but one can’t really rely on that due to unordered nature ofDictionary.Since
SequenceEqualwill compare the order as well, therefore relying on onlySequenceEqualcould be wrong. You have to useOrderByto order both dictionaries and then useSequenceEquallike:But that will involve multiple iterations, once for ordering and the other for comparing each element using
SequenceEqual.Code for overriding
EqualsandGetHashCodeYou may also see: Correct way to override Equals() and GetHashCode()