How to add dictionary to another dictionary?

Nitesh
Nitesh
2 Points
1 Posts

I have a dictionary that has some values in it, say:

Flowers <string, string>

I now receive another similar dictionary, say:

NewFlowers <string,string>

How can I append the entire NewFlowers dictionary to Flowers?

Views: 2209
Total Answered: 1
Total Marked As Answer: 0
Posted On: 12-Dec-2022 06:48

Share:   fb twitter linkedin
Add key-value pairs present in the given dictionary into the source dictionary.
 - Rahul Maurya  12-Dec-2022 23:30
Answers
beginer
beginer
1544 Points
52 Posts
         

we can use extension method like

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

And we can use it as:

Dictionary<string,string> flowers = new Dictionary<string,string>();
Dictionary<string,string> newflowers = new Dictionary<string,string>();

flowers.AddRange(newflowers);
Posted On: 13-Dec-2022 05:46
 Log In to Chat