Dictionary union
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | class Program { static void Main(string[] args) { //initialize a dictionary with keys and values. Dictionary<int, string> birds = new Dictionary<int, string>() { {1,"Caspian Tern"}, {2,"Plain Chachalaca"} }; Dictionary<int, string> birds2 = new Dictionary<int, string>() { {2,"Greater Rhea"}, {3,"Little Tinamou"} }; Console.WriteLine("dictionary keys and values.........."); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } Console.WriteLine("\ndictionary2 keys and values.........."); foreach (KeyValuePair<int, string> pair in birds2) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } //keep all elements from birds dictionary. Dictionary<int, string> result = birds; foreach (KeyValuePair<int, string> pair in birds2) { //this line check for duplicate keys. if (result.ContainsKey(pair.Key) == false) { //only unique key added in marged dictionary. result.Add(pair.Key, pair.Value); } } Console.WriteLine("\ndictionary union [keep all from dictionary1].........."); foreach (KeyValuePair<int, string> pair in result) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } //keep all elements from birds2 dictionary. Dictionary<int, string> result2 = birds2; foreach (KeyValuePair<int, string> pair in birds) { //this line check for duplicate keys. if (result2.ContainsKey(pair.Key) == false) { //only unique key added in marged dictionary. result2.Add(pair.Key, pair.Value); } } Console.WriteLine("\ndictionary union [keep all from dictionary2].........."); foreach (KeyValuePair<int, string> pair in result2) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } Console.ReadLine(); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | dictionary keys and values.......... 1 ........ Caspian Tern 2 ........ Plain Chachalaca dictionary2 keys and values.......... 2 ........ Greater Rhea 3 ........ Little Tinamou dictionary union [keep all from dictionary1].......... 1 ........ Caspian Tern 2 ........ Plain Chachalaca 3 ........ Little Tinamou dictionary union [keep all from dictionary2].......... 2 ........ Greater Rhea 3 ........ Little Tinamou 1 ........ Caspian Tern |