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

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

  • Trending Categories
  • Data Structure
  • Networking
  • RDBMS
  • Operating System
  • Java
  • MS Excel
  • iOS
  • HTML
  • CSS
  • Android
  • Python
  • C Programming
  • C++
  • C#
  • MongoDB
  • MySQL
  • Javascript
  • PHP
  • Physics
  • Chemistry
  • Biology
  • Mathematics
  • English
  • Economics
  • Psychology
  • Social Studies
  • Fashion Studies
  • Legal Studies
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary
  • Who is Who

CsharpServer Side ProgrammingProgramming

';

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:FRThe 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:CANValue 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.

Shilpa Nadkarni

Updated on: 22-Dec-2022

6K+ Views

  • Related Articles
  • C# Program to Get Key based on Value in Hashtable Collection
  • Get or Set the value associated with specified key in Hashtable in C#
  • Golang program to get value from the hash collection based on specified key
  • How to get hash code for the specified key of a Hashtable in C#?
  • Remove the element with the specified key from the Hashtable in C#
  • How to Delete Item from Hashtable Collection in C#?
  • Golang program to get key based on value from the hash collection
  • How to get keys from a HashTable in C#?
  • How to Create a HashTable Collection in C#?
  • How to Add Items to Hashtable Collection in C#
  • Get or set the value associated with specified key in ListDictionary in C#
  • Get or set the value associated with specified key in SortedList in C#
  • Java Program to Get key from HashMap using the value
  • Swift Program to Get key from Dictionary using the value
  • Get key from value in JavaScript
Kickstart Your Career

Get certified by completing the course

Get Started

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

Advertisem*nts

';

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

FAQs

How to Get Value from HashTable Collection in C# using 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];

How to get value from hashtable using key in C#? ›

Item[Object] Property is used to get or set the value associated with the specified key in the Hashtable. Here, key is key of object type whose value is to get or set.

How to retrieve value stored in hash table? ›

To retrieve the value associated with a key, apply the hash function to the key to determine the index. If the index contains a value, compare the stored key with the given key to ensure a match. If the keys match, return the corresponding value.

How to get hashtable value? ›

get() method of Hashtable class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the table contains no such mapping for the key.

How to get hash key-value? ›

Extracting Keys and Values from a Hash variable

The list of all the keys from a hash is provided by the keys function, in the syntax: keys %hashname . The list of all the values from a hash is provided by the values function, in the syntax: values %hashname . Both the keys and values function return an array.

How is a value retrieved using a hash key? ›

A hash table uses a hash function to convert the keys into hashes, and then stores the values in an array or a list at the corresponding index. This way, you can quickly access the value for any key by computing its hash and looking it up in the array or list.

What is the key-value store in a hash table? ›

A key–value database, or key–value store, is a data storage paradigm designed for storing, retrieving, and managing associative arrays, and a data structure more commonly known today as a dictionary or hash table.

Can you retrieve original data from its hash value? ›

Loss of Information: Hash functions lose some information from the original input data in order to produce the fixed-length output hash value. This loss of information makes it impossible to recover the original input data from the hash value.

Is Hashtable a key-value? ›

A hashtable is a data structure, much like an array, except you store each value (object) using a key. It's a basic key/value store.

How does a Hashtable work internally in C#? ›

A HashTable collection stores a ( Key , Value ) pair and uses the Key to hash and obtain the storage location. The Key is immutable and cannot have duplicate entries in the HashTable . This sample uses several instances of a simple Person class to store in a HashTable . The last name is used as the Key .

How to get key-value from hashtable in C#? ›

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];

How do you fetch a key-value? ›

get() method. We can get the value of a specified key from a dictionary by using the get() method of the dictionary without throwing an error, if the key does not exist. As the first argument, specify the key. If the key exists, the corresponding value is returned; otherwise, None is returned.

How to get value using C#? ›

GetValue() Method in C# is used to gets the value of the specified element in the current Array.

How to get key and value from HashMap? ›

Java HashMap Example

To get the key and value elements, we should call the getKey() and getValue() methods. The Map.Entry interface contains the getKey() and getValue() methods. But, we should call the entrySet() method of Map interface to get the instance of Map.Entry.

What is Hashtable key-value pair C#? ›

In the hashtable, you can store elements of the same type and of the different types. The elements of the hashtable that is a key/value pair are stored in DictionaryEntry, so you can also cast the key/value pairs to a DictionaryEntry. that key that must be unique. Duplicate keys are not allowed.

How do you check if a key is present in Hashtable? ›

containsKey() method is used to check whether a particular key is present in the Hashtable or not. It takes the key element as a parameter and returns True if that element is present in the table.

Top Articles
iCloud Keychain security overview
What Is Dwelling Coverage vs Home Insurance?
Summit County Juvenile Court
Voordelige mode in topkwaliteit shoppen
Kobold Beast Tribe Guide and Rewards
CKS is only available in the UK | NICE
Www Movieswood Com
Craigslist Jobs Phoenix
Cooking Fever Wiki
Walmart Windshield Wiper Blades
Saberhealth Time Track
Bnsf.com/Workforce Hub
Chastity Brainwash
Aldi Süd Prospekt ᐅ Aktuelle Angebote online blättern
Nick Pulos Height, Age, Net Worth, Girlfriend, Stunt Actor
Delaware Skip The Games
eHerkenning (eID) | KPN Zakelijk
Football - 2024/2025 Women’s Super League: Preview, schedule and how to watch
12 Facts About John J. McCloy: The 20th Century’s Most Powerful American?
Rs3 Ushabti
Yugen Manga Jinx Cap 19
Boise Craigslist Cars And Trucks - By Owner
2021 MTV Video Music Awards: See the Complete List of Nominees - E! Online
Beaufort 72 Hour
Safeway Aciu
Craigslist Brandon Vt
Busch Gardens Wait Times
Free Tiktok Likes Compara Smm
Mark Ronchetti Daughters
Was heißt AMK? » Bedeutung und Herkunft des Ausdrucks
Spy School Secrets - Canada's History
Why The Boogeyman Is Rated PG-13
Best Workers Compensation Lawyer Hill & Moin
Vanessa West Tripod Jeffrey Dahmer
Craigslist Georgia Homes For Sale By Owner
Nobodyhome.tv Reddit
Why Gas Prices Are So High (Published 2022)
7543460065
Tyler Perry Marriage Counselor Play 123Movies
VPN Free - Betternet Unlimited VPN Proxy - Chrome Web Store
60 Days From May 31
How to Install JDownloader 2 on Your Synology NAS
Paperlessemployee/Dollartree
Take Me To The Closest Ups
Definition of WMT
303-615-0055
Minecraft Enchantment Calculator - calculattor.com
Philasd Zimbra
Worlds Hardest Game Tyrone
Gainswave Review Forum
Dr Seuss Star Bellied Sneetches Pdf
Latest Posts
Article information

Author: Kerri Lueilwitz

Last Updated:

Views: 6517

Rating: 4.7 / 5 (47 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Kerri Lueilwitz

Birthday: 1992-10-31

Address: Suite 878 3699 Chantelle Roads, Colebury, NC 68599

Phone: +6111989609516

Job: Chief Farming Manager

Hobby: Mycology, Stone skipping, Dowsing, Whittling, Taxidermy, Sand art, Roller skating

Introduction: My name is Kerri Lueilwitz, I am a courageous, gentle, quaint, thankful, outstanding, brave, vast person who loves writing and wants to share my knowledge and understanding with you.