C# Program to Merge Two Hashtable Collections


The hashtable collection in C# stores key-value pairs. Each element or item in this collection is a key-value pair i.e. this collection is a double-element collection. The Key is unique, non-null, and used to access the elements in the hashtable.

The hashtable collection is immutable and cannot have duplicate elements. This means combination of key-value should be unique. However, the values can be null or duplicated. The .Net Framework provides a HashTable class to implement the hashtable collection and contains the required functionality to implement a hashtable without any additional coding.

Each element within the hashtable collection is a DictionaryEntry object having two properties: a key element and a value element. A hash code is generated automatically when an element is added to the hashtable. This hash code is internal and is hidden. The elements in the hashtable collection are sorted by the hidden hash code. Hence the hashtable elements are considered to be randomly selected.

With this brief introduction to the hashtable collection, let’s see how we can merge two hashtable collections.

How to Merge Two Hashtable Collections?

The Hashtable class is provided by System. The collection namespace contains only base class libraries that can be used to construct hashtable objects and perform operations like adding/removing elements, counting the number of elements, etc. There are no methods/functions provided that can be used to merge two hashtables together.

We have to devise our own approach to merge two hashtables. We know that the capacity or size of the hashtable is the number of elements the hashtable holds. As elements are inserted in the hashtable, the size of the hashtable grows automatically through reallocation.

Hence when we merge the two hashtables together, we will add elements of one hashtable to another hashtable. As we add elements the size of this hashtable will be adjusted accordingly.

The Approach

  • Create two hashtable objects.

  • Populate both tables with elements using Add method.

  • Traverse the second hashtable using the keys and add each of its key-value pairs to the first hashtable if the current item (key being traversed) is not already present in the first hashtable.

  • Print the resultant hashtable.

Note: We explicitly check if the key is present in the hashtable before adding it because the hashtable doesn’t allow the addition of duplicate keys.

Example

The above approach is converted into a C# program shown below.

using System;
using System. Collections;
class MyHashTable {
   static public void Main() {
      Hashtable indianNumberSystem = new Hashtable();
      indianNumberSystem.Add(1,"Ones");
      indianNumberSystem.Add(10,"Tens");
      indianNumberSystem.Add(100,"Hundred");
      indianNumberSystem.Add(1000,"Thousand");
      Console.WriteLine("Contents of indianNumberSystem hashtable:");
         foreach(DictionaryEntry ele1 in indianNumberSystem){
         Console.WriteLine("{0} ({1}) ", ele1.Key, ele1.Value);
      }
      Hashtable langCodes = new Hashtable();
      langCodes.Add("C++","CPlusPlus");
      langCodes.Add("C#","CSharp");
      langCodes.Add("Java","Java");
      langCodes.Add("PL","Perl");
      Console.WriteLine("
Contents of langCodes Hashtable:"); foreach(DictionaryEntry ele1 in indianNumberSystem){ Console.WriteLine("{0} ({1}) ", ele1.Key, ele1.Value); } foreach (DictionaryEntry entry in langCodes) { if(!indianNumberSystem.ContainsKey(entry.Key)) { indianNumberSystem.Add(entry.Key, entry.Value); }} Console.WriteLine("
Key, Value pairs after merging langCodes to indianNumberSystem:"); foreach(DictionaryEntry ele1 in indianNumberSystem){ Console.WriteLine("{0} ({1}) ", ele1.Key, ele1.Value); } } }

Here we have two hashtables namely, indianNumberSystem and langCodes.

The hashtable indianNumberSystem has the following data,

1

"Ones"

10

"Tens"

100

"Hundred"

1000

"Thousand"

The hashtable langCodes has the following data.

C++

"CPlusPlus"

C#

“CSharp"

Java

"Java"

PL

"Perl"

We first display the contents of both these tables. Then we traverse through the langCodes hashtable using its key. Inside the traversal loop, we first check if the hashtable indianNumberSystem has the same key. If the key is not present we add the element of langCodes pointed by the current key to the indianNumberSystem hashtable.

Output

Finally, we display the merged table.

Contents of indianNumberSystem hashtable:
1000 (Thousand)
10 (Tens)
100 (Hundred)
1 (Ones)
Contents of langCodes Hashtable:
1000 (Thousand)
10 (Tens)
100 (Hundred)
1 (Ones)
Key, Value pairs after merging langCodes to indianNumberSystem:
100 (Hundred)
1000 (Thousand)
PL (Perl)
10 (Tens)
C# (CSharp)
Java (Java)
C++ (CPlusPlus)
1 (Ones)

From the output generated we can see that both the tables merged correctly.

Example

Now let’s consider another example, the C# program which is given below.

using System;
using System. Collections;
using System.Collections.Generic;
class MyHashTable {
   static public void Main() {
      Hashtable indianNumberSystem = new Hashtable();
      indianNumberSystem.Add(1,"Ones");
      indianNumberSystem.Add(10,"Tens");
      indianNumberSystem.Add(100,"Hundred");
      indianNumberSystem.Add(1000,"Thousand");
      Console.WriteLine("Contents of indianNumberSystem hashtable:");
         foreach(DictionaryEntry ele1 in indianNumberSystem){
            Console.WriteLine("{0} ({1}) ", ele1.Key, ele1.Value);
      }
      Hashtable NumberNames = new Hashtable();
      NumberNames.Add(1,"One");
      NumberNames.Add(2,"Two");
      NumberNames.Add(3,"Three");
      NumberNames.Add(4,"Four");
      Console.WriteLine("
Contents of NumberNames Hashtable:"); foreach(DictionaryEntry ele1 in NumberNames){ Console.WriteLine("{0} ({1}) ", ele1.Key, ele1.Value); } foreach (DictionaryEntry entry in NumberNames) { if(!indianNumberSystem.ContainsKey(entry.Key)) { indianNumberSystem.Add(entry.Key, entry.Value); }} Console.WriteLine("
Key, Value pairs after merging NumberNames to indianNumberSystem:"); foreach(DictionaryEntry ele1 in indianNumberSystem){ Console.WriteLine("{0} ({1}) ", ele1.Key, ele1.Value); } } }

The program is the same as the previous one except that we have replaced the langCodes hashtable with the NumberNames hashtable. The NumberNames hashtable has the following elements.

1

"One"

2

“Two"

3

"Three

4

"Four"

Output

As we can see, the hashtables indianNumberSystem and NumberNames have common data. Now let’s execute this program to check how the merging happens.

Contents of indianNumberSystem hashtable:
1000 (Thousand)
10 (Tens)
100 (Hundred)
1 (Ones)
Contents of NumberNames Hashtable:
4 (Four)
3 (Three)
2 (Two)
1 (One)
Key, Value pairs after merging NumberNames to indianNumberSystem:
100 (Hundred)
1000 (Thousand)
10 (Tens)
4 (Four)
3 (Three)
2 (Two)
1 (Ones)

As seen from the above output, we can see the data element (key=1) in NumberNames is not added to the indianNumberSystem hashtable. This is because duplicates are not allowed.

Conclusion

Thus we can merge two hashtable collections by copying or adding the data of one hashtable to another. Whenever there is a common key present in both hashtables, the duplicate keys will not be added. But the programmer has to ensure that the check is made while adding data of one hashtable so that accidentally the data is not added as it will cause unpredictable results.

Updated on: 22-Dec-2022

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements