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

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

    (from a in foo
    join b in bar on a.Key equals b.Key
    select new { Key = a.Key, Value = a.Value + b.Value })
    .ToDictionary(a => a.Key,a => a.Value) 
    

    That should do it.

    EDIT: Might be more efficient (not sure how the join is implemented)

    (from a in foo
    let b = bar.ContainsKey(a.Key) ? (int?)bar[a.Key] : null
    select new { Key = a.Key, Value = a.Value + (b != null ? b : 0) }
    ).ToDictionary(a => a.Key, a => a.Value)
    

提交回复
热议问题