将字典添加到其他字典 [英] Adding a dictionary to another

查看:108
本文介绍了将字典添加到其他字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复项:
在C#中合并字典
这是什么最快的方法将值和键从一个字典复制到C#中的另一个字典中?

我有一本字典,里面有一些值,说:

I have a dictionary that has some values in it, say:

Animals <string, string>

我现在收到另一本类似的字典,说:

I now receive another similar dictionary, say:

NewAnimals <string,string>

如何将整个NewAnimals词典附加到Animals?

How can I append the entire NewAnimals dictionary to Animals?

推荐答案

foreach(var newAnimal in NewAnimals)
    Animals.Add(newAnimal.Key,newAnimal.Value)

注意:这会在重复键上引发异常.

Note: this throws an exception on a duplicate key.

或者,如果您真的想使用扩展方法route(我不愿意),则可以定义一个通用的 AddRange 扩展方法,该方法适用于任何 ICollection< T> ,而不仅仅是在 Dictionary< TKey,TValue> 上.

Or if you really want to go the extension method route(I wouldn't), then you could define a general AddRange extension method that works on any ICollection<T>, and not just on Dictionary<TKey,TValue>.

public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> source)
{
    if(target==null)
      throw new ArgumentNullException(nameof(target));
    if(source==null)
      throw new ArgumentNullException(nameof(source));
    foreach(var element in source)
        target.Add(element);
}

(抛出重复键的字典)

这篇关于将字典添加到其他字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆