[c#] Adding a dictionary to another

Possible Duplicates:
Merging dictionaries in C#
What's the fastest way to copy the values and keys from one dictionary into another in 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>

How can I append the entire NewAnimals dictionary to Animals?

This question is related to c#

The answer is


The most obvious way is:

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

Since Dictionary<TKey, TValue>explicitly implements theICollection<KeyValuePair<TKey, TValue>>.Addmethod, you can also do this:

var animalsAsCollection = (ICollection<KeyValuePair<string, string>>) Animals;

foreach(var kvp in NewAnimals)
   animalsAsCollection.Add(kvp);

It's a pity the class doesn't have anAddRangemethod likeList<T> does.


You can loop through all the Animals using foreach and put it into NewAnimals.


Create an Extension Method most likely you will want to use this more than once and this prevents duplicate code.

Implementation:

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

Usage:

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

animals.AddRange(newanimals);

The short answer is, you have to loop.

More info on this topic:

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