0

I have two dictionaries and I want to compare it against each other and they are of type Dictionary>

I tried using a foreach loop but it won't work exactly as desired.What's the best way to go about it?

foreach (KeyValuePair<string, Dictionary<string, object>> entry1 in dict1)
{
    foreach (KeyValuePair<string, Dictionary<string, object>> entry2 in dict2)
    {
        if (entry1.key = entry2.key)
        {
            if (entry1.Value["Number"]==entry2.Value["Number"])
            {
                Console.WriteLine("Comparison successful")
            }
        }
    }
}
Kinetic
  • 2,640
  • 17
  • 35
Shan
  • 2,822
  • 9
  • 40
  • 61

2 Answers2

1
public static Boolean CompareDictionary(Dictionary<string, object> D1, Dictionary<string, object> D2)
{
    if (D1 == null && D2 == null) return true;
    else if (D1 == null || D2 == null) return false;

    if (D1.Count != D2.Count) return false;    
    if (D1.Keys.Except(D2.Keys).Any()) return false;
    if (D2.Keys.Except(D1.Keys).Any()) return false;

    foreach (string Key in D1.Keys)
    {
        if (!D2.ContainsKey(Key)) return false;
        if (D1[Key] != D2[Key]) return false;
    }
    return true;
}
Zay Lau
  • 1,856
  • 1
  • 10
  • 17
  • This is also not working for me..as I need to compare the values of the one key from one dictionary against another key from another dictionary – Shan Sep 02 '16 at 02:45
  • @Shan: that's what the second `if` does inside the `foreach` loop. – siride Sep 02 '16 at 03:55
0

Here it is:

private static bool Check2DictionariesAreEqual(Dictionary<string, object> entry1, Dictionary<string, object> entry2)
{
    if(entry1 == null && entry2 == null)
    {
        return true;
    }
    else if(entry1 == null || entry2 == null)
    {
        return false;
    }

    if(entry1.Count != entry2.Count)
    {
        return false;
    }

    bool result = true;

    foreach (string key in entry1.Keys)
    {
        // Check Key
        result &= entry2.ContainsKey(key);

        if (!result) // Quick Break
        {
            break;
        }

        // Check Value
        result &= entry2[key] == entry1[key];

        if(!result) // Quick Break
        {
            break;
        }
    }

    return result;
}
kurakura88
  • 2,185
  • 2
  • 12
  • 18