Adding a dictionary to another [duplicate]

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?

0

5 Answers

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

Note: this throws an exception on a duplicate key.


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

(throws on duplicate keys for dictionaries)

6

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

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.

2

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#?

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

You Might Also Like