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?
Use == operator to check if the dictionaries are equal It will return True the dictionaries are equals and False if not.
When I had to compare two dictionaries for the first time, I struggled―a lot! For simple dictionaries, comparing them is usually straightforward. You can use the == operator, and it will work.
No... actually keys must be same in name and count.
Python List cmp() Method. The compare method cmp() is used in Python to compare values and keys of two dictionaries. If method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.
You can use
bool dictionariesEqual =
dic1.Keys.Count == dic2.Keys.Count &&
dic1.Keys.All(k => dic2.ContainsKey(k) && object.Equals(dic2[k], dic1[k]));
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