Home > Enterprise >  How to find the difference between two dictionaries (key and value) in LINQ
How to find the difference between two dictionaries (key and value) in LINQ

Time:10-19

I have 2 dictionaries.

One of which reports the added widgets (currentStatus), and the other is the default one (defaultDashboardWidgets)

private readonly Dictionary<string, int> defaultDashboardWidgets = new Dictionary<string, int>
        {
            { "Configure Dashboard widgets", 1 },
            { "Recent Items", 4 },
            { "System status widget", 1 },
            { "Dashboard Notifications", 1 },
            { "Welcome title", 1 },
            { "Welcome description", 1 }
        };

AND

private readonly Dictionary<string, int> currentStatus = new Dictionary<string, int>
        {
            { "Configure Dashboard widgets", 1 },
            { "Recent Items", 6 },
            { "System status widget", 1 },
            { "Dashboard Notifications", 1 },
            { "Welcome title", 1 },
            { "Welcome description", 1 },
            { "Images", 1 }
        };

I am trying to create a 3rd dictionary that contains the differences between the other two dictionaries.

The new Dictionary should look like this:

new Dictionary<string, int>
{
   {"Recent items", 2},
   {"Images", 1}
}

I am currently trying to achieve it via "Except", its return the different keys, but keeps the old value.

My Code:

var newDictionary = currentStatus.Except(this.defaultDashboardWidgets).ToDictionary(x => x.Key, x => x.Value)

And the result is :

{"Recent items", 6},
{"Images", 1}

CodePudding user response:

I suggest something like this, we compute difference for each Key and filter all non-zero Values (defaultDashboardWidgets doesn't have Key I've assumed the Value is 0):

var result = currentStatus
  .Select(pair => (key : pair.Key, 
                   value : pair.Value - defaultDashboardWidgets.TryGetValue(pair.Key, out int v) ? v : 0))
  .Where(pair => pair.value != 0)
  .ToDictionary(pair => pair.key, pair => pair.value);

CodePudding user response:

i would recommend a simple approach with a method:

 private static Dictionary<string, int> GetDifferences(Dictionary<string, int> currentDict, Dictionary<string, int> defaultDict)
    {
        Dictionary<string,int> thridDict = currentDict.Except(defaultDict).ToDictionary(x => x.Key, x => x.Value);

        foreach (var key in thridDict.Keys.ToList())
        {
            if (defaultDict.ContainsKey(key))
            {
                thridDict[key] = currentDict[key] - defaultDict[key];
            }
        }

        return thridDict;   
    }

the result is the expected: enter image description here

  • Related