How do I sum values from two dictionaries in C#?

后端 未结 6 1264
野性不改
野性不改 2020-12-19 00:51

I have two dictionaries with the same structure:

Dictionary foo = new Dictionary() 
{
    {\"Table\", 5 },
    {\"Chair         


        
6条回答
  •  盖世英雄少女心
    2020-12-19 01:34

    The following isn't the most efficient solution (because it simply treats both dictionaries as enumerables), but it will work and it is quite clear:

    Dictionary result = (from e in foo.Concat(bar)
                  group e by e.Key into g
                  select new { Name = g.Key, Count = g.Sum(kvp => kvp.Value) })
                  .ToDictionary(item => item.Name, item => item.Count);
    

提交回复
热议问题