Merging dictionaries in C#

前端 未结 26 1033
温柔的废话
温柔的废话 2020-11-22 08:25

What\'s the best way to merge 2 or more dictionaries (Dictionary) in C#? (3.0 features like LINQ are fine).

I\'m thinking of a method signa

26条回答
  •  既然无缘
    2020-11-22 08:58

    I would do it like this:

    dictionaryFrom.ToList().ForEach(x => dictionaryTo.Add(x.Key, x.Value));
    

    Simple and easy. According to this blog post it's even faster than most loops as its underlying implementation accesses elements by index rather than enumerator (see this answer).

    It will of course throw an exception if there are duplicates, so you'll have to check before merging.

提交回复
热议问题