Click here to Skip to main content
15,888,733 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need help finding out how i can merge 2 dictionaries together, creating one.



i have this code so far:

using System;
using System.Collections.Generic;

namespace merging_dictionaries
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>
            {
                { "WA", "Western Autralia" },
                { "NSW", "New South Wales" },
                { "SA", "South Australia" },
                { "Q", "Queensland" },
                { "V", "Victoria" },
                { "T", "Tasmania" }
            };

            Dictionary<string, string> otherdict = new Dictionary<string, string>
            {
                { "1", "Adclarkia dawsonensis" },
                { "2", "Advena campbellii " },
                { "3", "Discocharopa vigens" },
                { "4", "Hyridella glenelgensis" },
                { "5", "Mathewsoconcha grayi ms" },
                { "6", "Mathewsoconcha phillipii" }//these names are of endangered australian molusks, why not?
            };

            MergeDictionary(dict, otherdict);
        }

        public static Dictionary<string, string> MergeDictionary(Dictionary<string, string> dict1, Dictionary<string, string> dict2)
        {
            foreach (var thing in dict1)
            {
                dict2.Add(thing.Key);//make it do something with Add. 
                dict2.Add(thing.Value);//here i am trying to make it add the key and the value, but i have no idea how. 
            }
        }
    }
}


I can't make this work as intended, if at all.

Please help me fix it.

Thank you.

What I have tried:

I ave tried different ways of putting the dictionaries together with no success.

I have tried different ways of adding the keys and values, one at a time or all together, to no avail.
Posted
Updated 12-May-19 16:25pm
Comments
Maciej Los 12-May-19 9:06am    
My virtual 5!
BillWoodruff 12-May-19 22:15pm    
virtual +5

Check this thread: dictionary - Merging dictionaries in C# - Stack Overflow[^]. There's few ways to merge/combine dictionaries.

I'd improve them by adding line of code which will check if particular Key exists.

Good luck!
 
Share this answer
 
v2
Comments
[no name] 12-May-19 9:40am    
A 5
Maciej Los 12-May-19 9:48am    
Thank you, Bruno.
BillWoodruff 13-May-19 3:00am    
+5
Maciej Los 13-May-19 3:30am    
Thank you, Bill.
I needed something a little different that lets me specify ... in the case of duplicate Keys ... which Dictionary is the source of the value taken from the duplicate KeyValuePairs used in the merged output:
using System;
using System.Collections.Generic;
using System.Linq;

namespace WhatEver
{
    public static class DictionaryExtensions
    {
        public static Dictionary<TKey, TValue> Merge<TKey, TValue>(this Dictionary<TKey, TValue> dict1,
            Dictionary<TKey, TValue> dict2, bool useDupValueFromDict1 = true)
        {
            if (dict1.Equals(dict2)) throw new ArgumentException("duplicate dictionaries");

            if (dict1 == null) throw new ArgumentException("dictionary 1 is null");

            if (dict2 == null) throw new ArgumentException("dictionary 2 is null");

            if (dict1.Count == 0) throw new ArgumentException("dictionary 1 has no items");

            if (dict2.Count == 0) throw new ArgumentException("dictionary 2 has no items");

            Dictionary<TKey, TValue> result;
            IEnumerable<KeyValuePair<TKey, TValue>> nondups;

            if (useDupValueFromDict1)
            {
                result = dict1;
                nondups = dict2.Where(kvp => !dict1.ContainsKey(kvp.Key));

            }
            else
            {
                result = dict2;
                nondups = dict1.Where(kvp => !dict2.ContainsKey(kvp.Key));
            }

            return result.Union(nondups).ToDictionary(kvp1 => kvp1.Key, kvp1 => kvp1.Value);
        }
    }
}
Another variation (not shown here) lets you specify a comparison Func that will select which of the duplicate KeyValuePairs is used.
 
Share this answer
 
v2
Comments
Maciej Los 13-May-19 2:24am    
You did what i mentioned in my answer.
5ed!
BillWoodruff 13-May-19 3:00am    
I am always walking in the footprints of giants :) My motivation for writing this, a few years ago, was a need to control which Dictionary's values were used in the case of duplicate Keys.
[no name] 13-May-19 12:02pm    
A 5 for this.
BillWoodruff 13-May-19 21:23pm    
thank you !
You're using Add wrongly, you have to use it like this:
C#
dict2.Add(thing.Key, thing.Value);
 
Share this answer
 
Comments
Maciej Los 12-May-19 9:04am    
5ed!
[no name] 12-May-19 9:40am    
A 5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900