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

后端 未结 6 1263
野性不改
野性不改 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:18

    I wrote a little extension method that will merge a list of dictionaries with Int values. I used code from this question to do it so I am sharing

        public static Dictionary MergeIntDictionary( this ICollection> source )
        {
            return source.Aggregate( ( cur, next ) => cur.Concat( next )
                .GroupBy( o => o.Key )
                .ToDictionary( item => item.Key, item => item.Sum( o => o.Value ) ) );
        }
    

提交回复
热议问题