Detail We populate dictionaries with strings. The approach in this article would work on Dictionaries with any value type.
Detail A new HashSet is created from the Keys. This HashSet is unioned on the other 2 Dictionary Keys properties.
static void Main()
// First dictionary.
Dictionary<string, int> d1 = new Dictionary<string, int>();
// Second dictionary.
Dictionary<string, int> d2 = new Dictionary<string, int>();
// Third dictionary.
Dictionary<string, int> d3 = new Dictionary<string, int>();
// Get union of all keys.
HashSet<string> h1 = new HashSet<string>(d1.Keys);
// Display all the keys.// ... You can look up the values in the loop body.foreach (string k in h1)
A discussion. This code is fairly fast, but the performance has not been extensively tested. What the code does is clear. The UnionWith has a known effect.
Notes, built-in methods. Often we can solve a problem in C# with custom looping code. But built-in methods, like UnionWith on HashSet, tend to be more maintainable.
And If you didn't use HashSet, you would have to write more code. You could refactor the HashSet code into a method.
A summary. We use Hash Set with Dictionary keys to combine collections and find the union of the keys. HashSet has the ideal logic here.