Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a dictionary to another [duplicate]

Tags:

c#

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?

like image 287
xbonez Avatar asked Oct 20 '10 21:10

xbonez


People also ask

Can we add duplicate key dictionary?

It is not possible. All keys should be unique.

Can you append a dictionary to a dictionary in Python?

Use the update() Method to Add a Dictionary to Another Dictionary in Python. The update() method concatenates one dictionary to another dictionary. Using this method, we can insert key-value pairs of one dictionary to the other dictionary.

How many identical keys can a dictionary have?

No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.


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

like image 163
CodesInChaos Avatar answered Oct 11 '22 22:10

CodesInChaos


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); 
like image 28
Gabe Avatar answered Oct 11 '22 22:10

Gabe