94

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?

Community
  • 1
  • 1
xbonez
  • 40,730
  • 48
  • 157
  • 236

5 Answers5

117
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)

Henningsson
  • 1,255
  • 1
  • 16
  • 23
CodesInChaos
  • 103,479
  • 23
  • 206
  • 257
  • No problem. Duplicate keys are not a worry. – xbonez Oct 20 '10 at 21:42
  • I suggest you take a look at my solution and implement `AddRange`. I did all the work for you. – Gabe Oct 20 '10 at 21:46
  • @gmcalab: I do appreciate it, however this solution works just fine for me and is a lot smaller. I was really looking for something tiny that does the job. – xbonez Oct 21 '10 at 12:07
  • what kind of exception does it throw? just a plain Exception? – Netorica Jun 03 '15 at 14:52
  • 1
    @Mahan MSDN for the [`Dictionary.Add` Method](https://msdn.microsoft.com/en-us/library/k7z0zy8k.aspx) says `ArgumentException` - An element with the same key already exists in the `Dictionary`. – CodesInChaos Jun 03 '15 at 16:02
  • Why don't we do this to avoid ArguementException? `foreach ( var property in anotherProperties ) properties[property.Key] = property.Value;` – Brian Hong May 19 '21 at 19:20
39

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);
Gabe
  • 48,376
  • 28
  • 140
  • 179
12

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.

Ani
  • 107,182
  • 23
  • 252
  • 300
3

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

Community
  • 1
  • 1
automagic
  • 1,067
  • 8
  • 10
0

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

abhishek
  • 2,985
  • 22
  • 35