-1

Consider the code below, It is a list of Dictionaries merged to one Dictionary can this be written with linq?

    public static Dictionary<string, uint> mergeDictionaries(List<Dictionary<string, uint>> dictlist)
    {
        Dictionary<string, uint> mergedDict = new Dictionary<string, uint>();
        foreach (Dictionary<string, uint> dict in dictlist)
        {
            foreach (KeyValuePair<string, uint> entry in dict)
            {
                if (mergedDict.ContainsKey(entry.Key))
                {
                    mergedDict[entry.Key] = mergedDict[entry.Key] + entry.Value;
                }
                else
                {
                    mergedDict[entry.Key] = entry.Value;
                }
            }
        }
        return mergedDict;
    }
chatzich
  • 1,083
  • 2
  • 11
  • 26
  • 99% of the time when people use `ContainsKey` they should have used `TryGetValue`. This is such a time. – mjwills Sep 11 '19 at 21:41
  • The two dictionaries - are they using custom comparers (e.g. are they case insensitive)? – mjwills Sep 11 '19 at 21:42

1 Answers1

8
dictlist
    .SelectMany(dict => dict)
    .GroupBy(kvp => kvp.Key)
    .ToDictionary(g => g.Key, g => g.Sum(kvp => kvp.Value))
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • error CS1929: 'IGrouping>' does not contain a definition for 'Sum' and the best extension method overload 'Enumerable.Sum(IEnumerable)' requires a receiver of type 'IEnumerable' – chatzich Sep 12 '19 at 09:31
  • Oops; that should be `.Value`. Fixed. – SLaks Sep 16 '19 at 14:27