Search code examples
c#linqdictionarygeneric-collections

Sum values of a Dictionary for specific keys C#


I have a dictionary with two similar keys, one is misspelled so it created another key, that I would like to sum the values of, and delete the key/value pair that is misspelled.

If I have a dictionary of departments, with the department name as the key, and the number of personnel in that department as the value, I would like to sum the values for "Marketing" and "Marketin" and delete the misspelled key/value pair "Marketin".

        var departments = new Dictionary<string, int>()
        {
            { "HR", 33 },
            { "Management", 8 },
            { "Marketing", 21 },
            { "Marketin", 4 },
            { "Sales", 44 }
        };

I would like the dictionary to look like this:

        var departments = new Dictionary<string, int>()
        {
            { "HR", 33 },
            { "Management", 8 },
            { "Marketing", 25 },
            { "Sales", 44 }
        };

The dictionary is already created, so I only used an initialization for illustration purposes.


Solution

  • departments["Marketing"] += departments["Marketin"];
    
    departments.Remove("Marketin");