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?
It is not possible. All keys should be unique.
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.
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.
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)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With