C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: This is a complete console application that you can run in Visual Studio.
HashSetStrings: We populate dictionaries with strings. The approach in this article would work on Dictionaries with any value type.
Part D: A new HashSet is created from the Keys. This HashSet is unioned on the other 2 Dictionary Keys properties.
C# program that uses HashSet
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// A. First dictionary.
Dictionary<string, int> d1 = new Dictionary<string, int>();
d1.Add("cat", 1);
d1.Add("dog", 2);
// B. Second dictionary.
Dictionary<string, int> d2 = new Dictionary<string, int>();
d2.Add("cat", 3);
d2.Add("man", 4);
// C. Third dictionary.
Dictionary<string, int> d3 = new Dictionary<string, int>();
d3.Add("sheep", 5);
d3.Add("fish", 6);
d3.Add("cat", 7);
// D. Get union of all keys.
HashSet<string> h1 = new HashSet<string>(d1.Keys);
h1.UnionWith(d2.Keys);
h1.UnionWith(d3.Keys);
// E. Display all the keys.
// You can look up the values in the loop body.
foreach (string k in h1)
{
Console.WriteLine(k);
}
}
}
Output
cat
dog
man
sheep
fish