c# – How to compare two Dictionary<string,int> to find if any of the value has changed? – Education Career Blog

I have two dictionary personalizePatientChartDictionary and personalizePatientChartDictionaryOriginal. Both have same key but value can be different. I want to find out if there is any difference in value for a key. I have come up with the following function. Is there any better way of doing this? I am using .NET 4.0.

void CompareOriginalValues()
{
    foreach (KeyValuePair<string, int> Origkvp in personalizePatientChartDictionaryOriginal)
    {
        foreach (KeyValuePair<string, int> kvp in personalizePatientChartDictionary)
        {
            if ((Origkvp.Key == kvp.Key) && (Origkvp.Value != kvp.Value))
            {
                hasDictionaryChanged = true;
                break;
            }
        }
        if (hasDictionaryChanged)
        {
            break;
        }
    }
}

,

foreach (var kvp in personalizePatientChartDictionaryOriginal)
{
    int value;
    if (personalizePatientChartDictionary.TryGetValue(kvp.Key, out value))
    {
        if (kvp.Value != value)
        {
            hasDictionaryChanged = true;
            break;
        }
    }
}

Note that this code (and your original code) don’t detect if there are keys in one dictionary that aren’t present in the other. It only checks that the value associated with a particular key in the first dictionary is associated with the same key in the second dictionary, but only if that key actually exists in the second dictionary.

,

Seems good. But it would be good to return hasDictionaryChanged to indicate that it changed

,

You can do it using LINQ (don’t forget to add “using System.Linq” to your usings)

bool hasDictionaryChanged = personalizePatientChartDictionaryOriginal.Except(personalizePatientChartDictionary).Count() > 0;

For more information about what you can do with LINQ, see 101 LINQ Samples.

,

It would be possible to write your own version of the dictionary class, inherit from dictionary and IComparable.

Then you could do dictionary1.Compare(dictionary2);

Here is a good resource for the ICompareable interface
http://msdn.microsoft.com/en-us/library/system.icomparable.aspx

Leave a Comment