Home  >  Article  >  Backend Development  >  How to get value from HashTable collection in C# using specified key

How to get value from HashTable collection in C# using specified key

王林
王林forward
2023-08-28 23:09:06693browse

如何使用指定键从 C# 中的 HashTable 集合中获取值

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 to access a value in a hash table collection given a key.

How to get the value from the Hashtable collection using the specified key?

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

Consider the following hash table.

{“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 define a hash table. The user then enters the key for which the value is to be obtained. Once the key is read as input, we first determine if the key is null or empty. This is because the keys of the hash table should not be null. So if the user enters a null value, we won't continue looking for the value.

So if the key is not empty, we check if the hash table contains the specified key. To do this, we use the hash table collection method Contains() in C#, which returns true if the key exists in the hash table and false if the key does not exist.

If the Contains() method returns true, then we only need to access the value for that specific 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 FR. Since the key already exists in the hash table, the value corresponding to the key is returned successfully.

Now, what if we enter a key value that does not exist in the hash table?

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 hash table does not contain key=CAN, the program returns a message that the value does not exist.

In this way, we can develop an interactive program that finds the value of a specified key from a collection of hash tables.

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 we will also ask the user to enter the key to find the value, and then search the hash table 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 saw how to get a value from a hash table collection by key. We also show different outputs through several programming examples to clearly illustrate the concepts. In our next articles, we will continue to discuss the related topics of hash tables.

The above is the detailed content of How to get value from HashTable collection in C# using specified key. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete