How to get keys from a HashTable in C#?


The HashTable is a nongeneric collection in C#. It stores keyvalue pairs and is similar to a generic “Dictionary” collection. HashTable is defined in System.Collections.namespace.

HashTable consists of key/value pairs in which each key is computed as a hash code and stored in a different bucket internally. Whenever the HashTable is accessed, this hash code is matched to the hash code of the specified key and thus the corresponding values are accessed. This mechanism optimizes the lookup in the HashTable.

Let’s now discuss how to get keys from a HashTable in C#.

How to Get Keys from a HashTable?

We can get keys from a hashtable using two approaches.

  • Use a foreach loop and access the keys by iterating through hashtable

  • Retrieve a collection of keys from the hashtable and display them one by one.

Let’s demonstrate both these methods using examples.

Get Keys from HashTable using For-Each Loop

In this approach, we declare a hashtable with key/value pairs. Then using a for-each loop we display the keys in the hashtable.

To implement this programmatically, we will use the following hashtable.

{“US", "New York"}
{"FR", "Paris"}
{"UK", "London"}
{"IN", "Mumbai"}
{"GER", "Berlin"}

The above hashtable has country codes as keys and values as their corresponding important cities.

If the above hashtable is called Citytable, then we access its keys using the DictionaryEntry iterator as follows −

foreach(DictionaryEntry ele1 in Citytable){
        Console.WriteLine("{0}", ele1.Key);

This code will display each key in the hashtable.

Example 1

The full working program for this approach is given below −

using System;
using System.Collections;
class MyHashTable {
   // Main Method
   static public void Main() {
    
      // Create a hashtable instance
      Hashtable Citytable = new Hashtable();
      
      // Adding key/value pair in the hashtable using Add() method
      Citytable.Add("US", "New York");
      Citytable.Add("FR", "Paris");
      Citytable.Add("UK", "London");
      Citytable.Add("IN", "Mumbai");
      Citytable.Add("GER", "Berlin");
      
      //Print hashtable keys
      Console.WriteLine("Citytable Keys:");
      foreach(DictionaryEntry ele1 in Citytable){
         Console.WriteLine("{0}", ele1.Key);
      }      
   }
}

In this program, we declare and define a hashtable named, Citytable that contains country code and their important cities as key/value pairs respectively. Once the hashtable is populated with values using Add() method, we initiate a for-each loop that uses the iterator ‘ele1’ of type DictionaryEntry to iterate through the Citytable. Then for each iteration, the key value is printed.

Output

Citytable Keys:
FR
US
IN
GER
UK

As we can see, only the keys of the Citytable are displayed in the output. This is the most common approach as we mostly use a for-each loop to display the contents of any collection or array.

We can slightly modify the above program and have it display the corresponding values for the given keys.

For this, we will have to make the following change in the iterative loop.

foreach(DictionaryEntry ele1 in Citytable){
   Console.WriteLine("{0} = {1}", ele1.Key, ele1.Value);

In the above code, we are now also printing the Value part of the iterative counter.

Example 2

The full program for this modification is given below −

using System;
using System.Collections;
class MyHashTable {
   // Main Method
   static public void Main() {
    
      // Create a hashtable instance
      Hashtable Citytable = new Hashtable();
      
      // Adding key/value pair in the hashtable using Add() method
      Citytable.Add("US", "New York");
      Citytable.Add("FR", "Paris");
      Citytable.Add("UK", "London");
      Citytable.Add("IN", "Mumbai");
      Citytable.Add("GER", "Berlin");
      
      //Print hashtable keys
      Console.WriteLine("Citytable Keys:");
      foreach(DictionaryEntry ele1 in Citytable){
         Console.WriteLine("{0} = {1}", ele1.Key, ele1.Value);
      }      
   }
}

Output

Citytable Keys:
FR = Paris
US = New York
IN = Mumbai
GER = Berlin
UK = London

Thus, here we have displayed the key/value pairs for the Citytable.

Let’s move on to the next approach.

Using Collection

In this approach, we use a collection first to get the collection of keys from Hashtable and then print these keys. The keys are printed as string values which are nothing but the elements of the collection.

Let’s take an example of a hashtable for programming languages.

{"CPP", "C++"}
{"CS", "C#"}
{"JAVA", "JAVA"}
{"PL", "PERL"}
{"JS", "JAVASCRIPT"}

We define the above table as a hashtable, Langtable in our program. Then we declare an ICollection object ‘keys’ and collect the hashtable keys in this object.

ICollection keys = Langtable.Keys;

Once we get the keys collection, we can then iterate through this collection easily and display each key as a string.

foreach (String k in keys){
   Console.WriteLine(k);
}

In this way, we can display each key in the hashtable individually.

Example

The complete program for this approach is given here.

using System;
using System.Collections;
class MyHashTable {
   // Main Method
   static public void Main() {
    
      // Create a hashtable instance
      Hashtable Langtable = new Hashtable();
      
      // Adding key/value pair in the hashtable using Add() method
      Langtable.Add("CPP", "C++");
      Langtable.Add("CS", "C#");
      Langtable.Add("JAVA", "JAVA");
      Langtable.Add("PL", "PERL");
      Langtable.Add("JS", "JAVASCRIPT");
      
      //Collection of Hashtable keys
      ICollection keys = Langtable.Keys;

      Console.WriteLine("Language Keys:");
      foreach (String k in keys){
         Console.WriteLine(k);
      }
      Console.ReadKey();
   }
}

As already discussed, the above program contains a hashtable of programming languages with the language code as keys and their names as values. We first retrieve a collection of keys from the hashtable using an ICollection object. Then we iterate through this object and display keys one by one.

Output

Language Keys:
PL
JS
CS
JAVA
CPP

So the program displays the language code (keys) for the hashtable. Again if we want the corresponding value for each key, we can just print it by accessing the hashtable with the given key. We leave this modification to the reader.

Thus we can get(access) the hashtable keys from a hashtable using any of the two approaches we discussed above. Though both approaches are straightforward, we mostly use the first approach of iterating through the hashtable using a for-each loop for most of the collections.

In the subsequent articles, we will discuss more Hashtable operations that can be performed in C#.

Updated on: 14-Dec-2022

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements