Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two dictionaries for equal data in c#?

Tags:

c#

.net-3.5

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?

like image 417
mezamorphic Avatar asked Nov 20 '12 09:11

mezamorphic


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 two dictionaries be compared?

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.

Can we compare two dictionaries in C#?

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

How do you compare keys in two dictionaries?

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.


1 Answers

You can use

bool dictionariesEqual = 
    dic1.Keys.Count == dic2.Keys.Count &&
    dic1.Keys.All(k => dic2.ContainsKey(k) && object.Equals(dic2[k], dic1[k]));
like image 134
Rawling Avatar answered Sep 22 '22 07:09

Rawling