Home > OS >  Find the difference between two dictionaries
Find the difference between two dictionaries

Time:12-16

I have following code for comparing 2 dicts. In dicts can be multiple keys with different or the same value. If 2 dicts are completely same i should return true. If there is some difference(ex. not existing key in dict1, but existing in dict2, or values of the same keys are different - false. So the problem of this code is in case i add to dict1 or vice versa i add new KeyValuePair, or keys are not ordered to compare them, it will be not correct return for the method. So basicaly i need properly compare 2 dictionaries which can be completely different with keys and values or the same one. Ordering of KeyValuePairs in dicts can be also different in both.

public static bool FlagsAreEqual(Dictionary<string, string> currentEntity, Dictionary<string, string> changedEntity)
    {
        var equals = false;
        foreach (KeyValuePair<string, string> kvp in currentEntity)
        {
            if (changedEntity.Contains(kvp))
            {
                equals = true;
            }
            else
            {
                equals = false;
            }
        }

        return equals;
    }

public static void Main()
{
    var dicOne = new Dictionary<string, string>() { { "asdf", "asdf" }, { "few", "faew" } };
    var dicTwo = new Dictionary<string, string>() { { "asdf", "asdf" }, { "few", "aaa" } };

    if (!FlagsAreEqual(dicOne, dicTwo))
    {
        Console.WriteLine("update");
    }
    else
    {
        Console.WriteLine("not update");
    }

    Console.ReadKey();
}

CodePudding user response:

I suggest something like this:

using System.Linq;

...

public static bool FlagsAreEqual<K, V>(Dictionary<K, V> currentEntity, 
                                       Dictionary<K, V> changedEntity) {
  // currentEntity and changedEntity share the same reference
  if (ReferenceEquals(currentEntity, changedEntity))
    return true;
  // one of dictionaries (but not both - since ReferenceEquals is not true) is null
  if (currentEntity is null || changedEntity is null)
    return false;
  // there are added / removed keys
  if (currentEntity.Keys.Count != changedEntity.Key.Count)
    return false;

  // finally, each currentEntity key has corresponding changedEntity one
  // with equal value
  return currentEntity.All(pair =>
    changedEntity.TryGetValue(pair.Key, out var value) && Equals(value, pair.Value));
}
  • Related