【问题标题】:Adding a dictionary to another [duplicate]将字典添加到另一个[重复]
【发布时间】:2011-04-28 07:14:53
【问题描述】:

可能的重复:
Merging dictionaries in C#
What's the fastest way to copy the values and keys from one dictionary into another in C#?

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

Animals <string, string>

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

NewAnimals <string,string>

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

【问题讨论】:

    标签: c#


    【解决方案1】:
    foreach(var newAnimal in NewAnimals)
        Animals.Add(newAnimal.Key,newAnimal.Value)
    

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


    或者如果你真的想走扩展方法路线(我不会),那么你可以定义一个通用的AddRange 扩展方法,它适用于任何ICollection&lt;T&gt;,而不仅仅是Dictionary&lt;TKey,TValue&gt;

    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);
    }
    

    (为字典抛出重复键)

    【讨论】:

    • 没问题。不必担心重复键。
    • 我建议你看看我的解决方案并实施AddRange。我为你做了所有的工作。
    • @gmcalab:我很感激,但是这个解决方案对我来说很好,而且要小得多。我真的在寻找可以完成这项工作的小东西。
    • 它会抛出什么样的异常?只是一个普通的例外?
    • @Mahan MSDN for the Dictionary&lt;TKey, TValue&gt;.Add MethodArgumentException - Dictionary&lt;TKey, TValue&gt; 中已经存在具有相同键的元素。
    【解决方案2】:

    创建一个扩展方法,您很可能会想要多次使用它,这样可以防止重复代码。

    实施:

     public static void AddRange<T, S>(this Dictionary<T, S> source, Dictionary<T, S> collection)
     {
            if (collection == null)
            {
                throw new ArgumentNullException("Collection is null");
            }
    
            foreach (var item in collection)
            {
                if(!source.ContainsKey(item.Key)){ 
                   source.Add(item.Key, item.Value);
                }
                else
                {
                   // handle duplicate key issue here
                }  
            } 
     }
    

    用法:

    Dictionary<string,string> animals = new Dictionary<string,string>();
    Dictionary<string,string> newanimals = new Dictionary<string,string>();
    
    animals.AddRange(newanimals);
    

    【讨论】:

    • 为什么不键入正确的参数为IEnumerable&lt;KeyValue&lt;TKey,TValue&gt;&gt;?为什么键和值只使用一个通用参数?
    • @CodesInChaos,将第二个参数设置为 IEnumerable> 有什么意义?具体用例?
    • 我添加了公共枚举 OnDuplicateKey { Throw, Skip, Replace }
    • @vkelman 1) 任何字典都能满足 2) 我有时会通过 Linq 生成序列,然后我想将其添加到字典中。
    【解决方案3】:

    最明显的方式是:

    foreach(var kvp in NewAnimals)
       Animals.Add(kvp.Key, kvp.Value); 
      //use Animals[kvp.Key] = kvp.Value instead if duplicate keys are an issue
    

    由于Dictionary&lt;TKey, TValue&gt;明确实现了ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.Add方法,你也可以这样做:

    var animalsAsCollection = (ICollection<KeyValuePair<string, string>>) Animals;
    
    foreach(var kvp in NewAnimals)
       animalsAsCollection.Add(kvp);
    

    可惜这个类没有AddRange方法像List&lt;T&gt;一样。

    【讨论】:

    • 同意。 AddRange 很方便。
    • 这就是您编写扩展方法的原因,这是该问题的最佳解决方案,但OP并未选择。意大利面条代码啊!
    【解决方案4】:

    简短的回答是,你必须循环。

    有关此主题的更多信息:

    What's the fastest way to copy the values and keys from one dictionary into another in C#?

    【讨论】:

      【解决方案5】:

      您可以使用 foreach 遍历所有 Animals 并将其放入 NewAnimals。

      【讨论】:

        猜你喜欢
        • 2018-07-27
        • 1970-01-01
        • 1970-01-01
        • 2022-07-10
        • 1970-01-01
        • 1970-01-01
        • 2018-08-19
        • 1970-01-01
        • 2016-04-14
        相关资源
        最近更新 更多