Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to Get Key based on Value in Hashtable Collection
A hashtable is a collection in C# that holds items identified as key-value pairs. Unlike other data structures like the stack, queue, or ArrayList that store a single value, a hashtable stores two values that form an element the key and the value.
In a hashtable, the keys are unique and cannot be null. The values can be null and duplicated. The System.Collections namespace provides the Hashtable class with various constructors, methods, and properties to perform operations on hashtable objects.
This article demonstrates how to retrieve a key from a hashtable collection based on a specific value.
How to Get a Key Based on Value
The Hashtable class has no direct method to get a key based on its value. We need to implement our own logic by traversing the hashtable, comparing each value with the specified value, and returning the corresponding key when a match is found.
The approach involves using a foreach loop to iterate through all keys in the hashtable, then checking if each key's value matches our target value
foreach (string key in hashtable.Keys) {
if (hashtable[key].ToString() == targetValue) {
return key;
}
}
Using foreach Loop to Find Key by Value
Example
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;
break; // Exit loop when found
}
}
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);
}
}
}
The output of the above code is
Key for the value = CSharp is C#
Searching for Non-Existent Value
If we search for a value that doesn't exist in the hashtable, like "JavaScript", the program will indicate that no matching key was found
using System;
using System.Collections;
class Program {
public static void Main() {
Hashtable langCodes = new Hashtable();
langCodes.Add("C++", "CPlusPlus");
langCodes.Add("C#", "CSharp");
langCodes.Add("Java", "Java");
langCodes.Add("PL", "Perl");
string value = "JavaScript";
string retKey = "";
foreach (string key in langCodes.Keys) {
if (langCodes[key].ToString() == value) {
retKey = key;
break;
}
}
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);
}
}
}
The output of the above code is
Key for the value = JavaScript is not present in the Hashtable
Handling Null Values
Since hashtables allow null values, you can also search for keys that contain null values
Example
using System;
using System.Collections;
class Program {
public static void Main() {
Hashtable myHashTable = new Hashtable();
// Add elements including empty string
myHashTable.Add("First", "Hello");
myHashTable.Add("Second", "World");
myHashTable.Add("Third", "");
myHashTable.Add("Fourth", "!");
string value = ""; // Search for empty string
string retKey = "";
foreach (string key in myHashTable.Keys) {
if (myHashTable[key].ToString() == value) {
retKey = key;
break;
}
}
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);
}
}
}
The output of the above code is
Key for the value = '' is Third
Using Helper Method for Reusability
Example
using System;
using System.Collections;
class Program {
public static string GetKeyByValue(Hashtable hashtable, object targetValue) {
foreach (object key in hashtable.Keys) {
if (hashtable[key].Equals(targetValue)) {
return key.ToString();
}
}
return null; // Key not found
}
public static void Main() {
Hashtable studentGrades = new Hashtable();
studentGrades.Add("Alice", 95);
studentGrades.Add("Bob", 87);
studentGrades.Add("Charlie", 92);
studentGrades.Add("Diana", 87);
string foundKey = GetKeyByValue(studentGrades, 87);
if (foundKey != null) {
Console.WriteLine("First key with value 87: {0}", foundKey);
} else {
Console.WriteLine("No key found with value 87");
}
// Find key for a different value
foundKey = GetKeyByValue(studentGrades, 95);
Console.WriteLine("Key with value 95: {0}", foundKey);
}
}
The output of the above code is
First key with value 87: Bob Key with value 95: Alice
Key Points
-
Hashtables do not provide a built-in method to find keys by values.
-
Use
foreachloop withhashtable.Keysto iterate through all keys. -
Compare values using
.ToString()or.Equals()methods. -
If multiple keys have the same value, the method returns the first match found.
-
Always handle cases where the target value might not exist in the hashtable.
Conclusion
Finding a key based on its value in a hashtable requires iterating through all key-value pairs and comparing each value with the target. While there's no direct method for this operation, using a foreach loop provides an efficient solution for retrieving keys based on their associated values.
