How to Get Value from HashTable Collection in C# using Specified Key


A hashtable is a collection of key−value pairs. We can access key−value pairs using an iterator. We can also access the keys of the hashtable in a collection. Similarly, we can access the values in a hashtable. Given a hashtable, it is also possible to access the value of a specified key or matching key of a specified value.

Let’s discuss how we can access a value from the hashtable collection given a key.

How to Get Value from Hashtable Collection using Specified Key?

Here, we have to obtain a value from the key−value pair of hashtables when a key is given.

Consider following the hashtable.

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

Here, let’s suppose we have to find the value for the key “UK”. So we have to traverse the hashtable to find out if the hashtable contains the key = UK. Once the key=” UK” is found, we can access its corresponding value as hashtable[key].

Example

The program that exactly performs the above operation is shown 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");
      
      String key;
      Console.WriteLine("Enter the key whose value is to be printed:");
      key = Console.ReadLine();
      if(key != ""){
         if(Citytable.Contains(key) == true){
         string keyval = (string)Citytable[key];
         Console.WriteLine("The value of key {0} = {1}", key,keyval);
      }
      else
         Console.WriteLine ("Value for the key= {0} does not exist", key);
      }    
      Console.ReadKey();
   }
}

In the above program, we have defined a hashtable. Then the user enters the key for which the value is to be obtained. Once the key is read as an input, we first determine if the key is null or empty. This is because hashtable keys should not be null. So if the user enters an empty value we will simply not proceed with finding the value.

Thus if the key is not empty, we check if the hashtable contains the specified key. To do this we use the hashtable collection method in C#, Contains() that returns true if the key is present in the hashtable or false if the key is not present.

If Contains() method returns true, then we simply access the value of that particular key.

string keyval = (string)Citytable[key];

Then this value is displayed to the user.

Output

Enter the key whose value is to be printed:
FR
The value of key FR = Paris

In this output, the user executed the program and entered the key value as FR. Since this key is already present in the hashtable, the value for that key is successfully returned.

Now if we enter a key value that is not present in the hashtable?

Let’s execute the program again. Now we do not have a key in our hashtable for the country Canada. Let’s enter the key as CAN for Canada. The output is shown below.

Output

Enter the key whose value is to be printed:
CAN
Value for the key= CAN do not exist

Here, since the hashtable does not contain the key=CAN, the program returns the message that the value does not exist.

In this manner, we can develop an interactive program to find the value of a specified key from a hashtable collection.

Let’s take another example to find the value given a key using a hashtable.

Here we will consider the following hashtable containing numbers and their corresponding number names.

{“1.1", "One point One"}
{"1.2", "One point Two"}
{"1.3", "One point Three"}
{"1.4", "One point Four"}
{"1.5", "One point Five"}

Similar to the previous example, here also we will ask the user to enter the key for which value is to be found and then search the hashtable for the specified key and display its value.

Example 2

Below given is the program to do that same.

using System;
using System.Collections;
class MyHashTable {
   // Main Method
   static public void Main() {

      // Create a hashtable instance
      Hashtable Numbernames = new Hashtable();

      // Adding key/value pair in the hashtable using Add() method
      Numbernames.Add("1.1", "One point One");
      Numbernames.Add("1.2", "One point Two");
      Numbernames.Add("1.3", "One point Three");
      Numbernames.Add("1.4", "One point Four");
      Numbernames.Add("1.5", "One point Five");

      String key = "1.4";
      if(key != ""){
          if(Numbernames.Contains(key) == true){
              string keyval = (string)Numbernames[key];
              if(keyval != "")
                 Console.WriteLine("The value of key {0} = {1}", key,keyval);
              else
                 Console.WriteLine("The value for key = {0} does not exist", key);
          }
          else
             Console.WriteLine ("The key= {0} does not exist in the NumberNames hashtable", key);
      }    
      Console.ReadKey();
   }
}

The program is the same as the previous example except for the hashtable and an extra condition we have specified to check for an empty value. This is because it can so happen that a specified key might be present in the hashtable, but its corresponding value might be empty. Secondly, we are not reading user input in this program, instead, we have directly used a key = “1.4” and we print out the value of this key. So we introduced one more check in this program. Hence this program now checks −

  • If the key specified is empty

  • If the key is not empty, the program checks if the hashtable contains the key.

  • If the hashtable contains the key, then it retrieves the value for the key. If the value is not empty, then the program displays the value.

  • If the value is empty, the appropriate message is displayed.

Output

The value of key 1.4 = One point Four

This output is generated when we specify a correct key that is present in the hashtable.

In this article, we have seen how we can get value from a hashtable collection given the key. We also saw a couple of programming examples with different outputs to clear the concept. In our subsequent articles, we continue with hashtable topics.

Updated on: 22-Dec-2022

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements