Home > database >  Efficient way to create a new list based of the differences in values in 2 dictionaries?
Efficient way to create a new list based of the differences in values in 2 dictionaries?

Time:07-14

I currently have 2 strings that are formatted as an XML that are later converted into dictionaries for comparison.

So, I have a 2 Dictionary<string, object>, dict1 and dict2, that I need to compare. I need to:

  1. Add the key to a list of strings if the values of these two dictionaries do not match
  2. Add the key of dict2 to the list if dict1 does not contain this key

Currently, I have a simple foreach loop


foreach (string propName in dict2.Keys)
{
    string oldDictValue;
    string newDicValue = dict1[propName].ToString();
    if (dict1.ContainsKey(propName))
    {
        oldDictValue = dict2[propName].ToString();
        if (oldDictValue != newDicValue)
            list.Add(propName);
    }
    else
    {
        list.Add(propName);
    }

}

I would like to a faster solution to this problem if possible?

CodePudding user response:

I don't claim that this is any faster, but it should be on par and it's less code:

List<string> list =
    dict2
        .Keys
        .Where(k => !(dict1.ContainsKey(k) && dict1[k].Equals(dict2[k])))
        .ToList();

I did do some testing with this:

List<string> list =
    dict2
        .Keys
        .AsParallel()
        .Where(k => !(dict1.ContainsKey(k) && dict1[k].Equals(dict2[k])))
        .ToList();

That produced a significantly faster run.

Here's how I produced my test data:

var dict1 = Enumerable.Range(0, 10000000).Select(x => Random.Shared.Next(2000000)).Distinct().ToDictionary(x => x.ToString(), x => (object)Random.Shared.Next(20));
var dict2 = Enumerable.Range(0, 10000000).Select(x => Random.Shared.Next(2000000)).Distinct().ToDictionary(x => x.ToString(), x => (object)Random.Shared.Next(20));
  • Related