
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
C# Program to Get Key based on Value in Hashtable Collection
A hash table is a collection in C# that holds items identified as key-value pairs. So unlike other data structures like the stack, queue, or ArrayList in C# that store a single value, hashtable in C# stores 2 values. These 2 values i.e. key-value pair form an element of the hash table.
In a hashtable, the keys are unique and should not be null. The values in the hashtable can be null and also duplicated.
In C#, the System.collections interface provides a class “Hashtable” which is used to represent the hashtable collection. This class provides various constructors to create a hashtable object and also methods and properties to perform various operations on the hashtable object.
In this article, we will see how to get a key in a hashtable collection based on a value.
How to Get a Key Based on Value in Hashtable Collection?
The Hashtable class has no direct method to get a key based on the value in the hashtable. So we need to program the hashtable collection so that we retrieve the key given a value.
Let’s discuss the approach to getting a key based on value. For this, we traverse the entire hashtable based on hashtable keys. Then we match each value with the specified value and if the values match, we return the corresponding key.
For traversing the hashtable, we can use the foreach loop as follows.
foreach (string key in langCodes.Keys) { if (langCodes[key].ToString() == value) { retKey = key; } }
The iterator we use in the foreach loop to traverse the hashtable is the collection of keys (langCodes.Keys). The corresponding value for each key C# Program to Get Key based on Value in Hashtable Collection is then compared to the specified value and if there is a match, the particular key is returned.
Example
The program below shows this implementation.
using System; using System.Collections; class Program { public static void Main(){ // Create a Hashtable Hashtable langCodes = new Hashtable(); // Add elements to the Hashtable langCodes.Add("C++", "CPlusPlus"); langCodes.Add("C#", "CSharp"); langCodes.Add("Java", "Java"); langCodes.Add("PL", "Perl"); string value = "CSharp"; string retKey=""; foreach (string key in langCodes.Keys){ if (langCodes[key].ToString() == value){ retKey = key; } } if(retKey != ""){ Console.WriteLine("Key for the value = {0} is {1}", value,retKey); } else { Console.WriteLine("Key for the value = {0} is not present in the Hashtable", value); } } }
Here, we have a hashtable named, “langCodes” consisting of programming language codes with their corresponding values. A string variable is declared that contains the specified value. Then using the foreach construct we traverse the entire hashtable and check for the key which has the value same as the specified value. When one such key is found, that key value is returned in a variable retKey.
Output
If the variable retKey has a value in it, we output that value as a key for the specified value. If retKey is empty then it is concluded that
Key for the value = CSharp is C#
Now let’s say we want to get a key for the value = “JavaScript”.
string value = "JavaScript";
Output
With this change, we execute the above program and it generates the following output.
Key for the value = JavaScript is not present in the Hashtable
Now since the hashtable does not have any matching element for JavaScript language, the program displays the above message.
Let’s take another example to simplify the topic.
Example
The following program gets a key in the hashtable given a specific value.
using System; using System.Collections; class Program { public static void Main() { // Create a Hashtable Hashtable myHashTable = new Hashtable(); // Add elements to the Hashtable myHashTable.Add("First", "Hello"); myHashTable.Add("Second", "World"); myHashTable.Add("Third", ""); myHashTable.Add("Fourth", "!"); string value = ""; string retKey=""; foreach (string key in myHashTable.Keys) { if (myHashTable[key].ToString() == value) { retKey = key; } } if(retKey != ""){ Console.WriteLine("Key for the value = {0} is {1}", value,retKey); } else { Console.WriteLine("Key for the value = {0} is not present in the Hashtable", value); } } }
In this program, we have a hashtable ‘myHashTable’ which stores the famous quote “Hello World!”. But we have not stored the words continuously. Instead, we introduced a null value after the word ‘World’.
Output
The program aims to get the key for the null value. The output that is generated is given below.
Key for the value = is Third
Here, since the null values are permitted in the hashtable, when we specify a null value, the corresponding key for the null value is retrieved.
Now let’s change the value we want to get the key for. Below we change the value to ‘!’ and execute the program.
string value = "!";
Output
Key for the value = ! is Fourth
The third element in the hashtable is a null value hence the last part of the quote is the having the fourth position in the hashtable.
In this manner, we can program the hashtable to retrieve the key given a specific value in the hashtable. As we have already seen, since the hashtable allows null values, we can also pass a null value and get its corresponding key.
- Related Articles
- Golang program to get key based on value from the hash collection
- How to Get Value from HashTable Collection in C# using Specified Key
- JavaScript - Sort key value pair object based on value?
- Get or Set the value associated with specified key in Hashtable in C#
- C# Program to find a key in a Hashtable
- Time Based Key-Value Store in C++
- Java Program to Get key from HashMap using the value
- C# Program to Check a HashTable collection is empty or not
- Count the number of key/value pairs in the Hashtable in C#
- How to Create a HashTable Collection in C#?
- C# Program to find a value in a Hashtable
- C# Program to Check if Value exists in Hashtable
- How to get hash code for the specified key of a Hashtable in C#?
- Add key and value into OrderedDictionary collection in C#
- How to Add Items to Hashtable Collection in C#
