Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two Dictionary<string,int> to find if any of the value has changed?

Tags:

c#

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;
        }
    }
}
like image 720
Rohit Raghuvansi Avatar asked Dec 29 '22 06:12

Rohit Raghuvansi


2 Answers

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.

like image 73
LukeH Avatar answered Feb 15 '23 18:02

LukeH


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

like image 40
Ash Avatar answered Feb 15 '23 20:02

Ash