How to store/update Hashtable Elements? (2024)

CsharpServer Side ProgrammingProgramming

A hashtable is a data structure that consists of a collection of key-value pairs. The hashtable collection uses a hash function to compute the hash code of the key. A hashtable can also be defined as a non-generic collection of key-value pairs.

The hash code of each key is computed using a hash function and is stored in a different bucket internally. At the time of accessing values, this hash code is matched with that of the specified key, and results are returned.

Unlike other data structures like the stack, queue, ArrayList, etc. that store single values, hashtable collection stores double values in the form of keyvalue pairs. Each pair of key-value form an element of the hashtable.

Let’s discuss how to store and update elements in the hashtable collection in this article.

How to Store/Update items in Hashtable?

We can store or add elements in the hashtable and also update existing elements in the hashtable. These are two different actions that we can perform on the hashtable collection.

As far as the addition of elements to the hashtable collection is concerned, we make use of the “Add” method of the Hashtable class provided in C#.

For updating the elements of the hashtable, we use the assignment operator to replace the values.

Adding elements to the hashtable

There are two ways in which we can add elements to the hashtable.

  • Using intiliazer for hashtable

  • Using Add method

In the first method of using an initializer, we initialize the hashtable object with the key-value pairs when declaring the hashtable object.

This creates a hashtable object with the initial key-value pairs. Let’s take a programming example to demonstrate adding elements to the hashtable using initialization.

Example

using System;using System.Collections;class MyHashTable { public static void Main() { // Create a Hashtable Hashtable prog_lang = new Hashtable(){{"001", "C#"}, {"002", "C++"}, {"003", "Java"}, {"004", "Python"}, {"005", "Perl"} }; //print original hashtable Console.WriteLine("Hashtable items:"); foreach(DictionaryEntry entry in prog_lang){ Console.WriteLine("{0} => {1} ", entry.Key, entry.Value); } }}

In this example, first, we create an object of type Hashtable named ‘prog_lang’ with the ‘new’ keyword and initialize it to five key-value pairs of numbers(keys) and the programming language names (values).

Then we print the contents of this hashtable by traversing the hashtable using the ‘foreach’ loop.

Output

This program generates the following.

Hashtable items:005 => Perl 004 => Python 002 => C++ 003 => Java 001 => C# 

The program simply displays the contents of the hashtable.

The Add method is provided by the Hashtable class and can be used to add elements to the Hashtable object. The Add method has the following general syntax.

HashTable.add("key", "value")

Example

The following program demonstrates the Add method for storing elements in the hashtable collection.

using System;using System.Collections;class MyHashTable { public static void Main() { // Create a Hashtable Hashtable prog_lang = new Hashtable(); prog_lang.Add("001", "C#"); prog_lang.Add("002", "C++"); prog_lang.Add("003", "Java"); prog_lang.Add("004", "Python"); prog_lang.Add("005", "Perl"); //print original hashtable Console.WriteLine("Hashtable items:"); foreach(DictionaryEntry entry in prog_lang){ Console.WriteLine("{0} => {1} ", entry.Key, entry.Value); } }}

The program is similar to the previous one except that here we have used Add method to add elements to the hashtable. So here we add the same five elements consisting of numbers(keys) and programming language names (values) to the hash table and then display the contents of the hashtable.

Output

The output of the program is shown below.

Hashtable items:005 => Perl 004 => Python 002 => C++ 003 => Java 001 => C# 

As shown, the contents of the hashtable are displayed in the output.

Updating elements in the Hashtable

The elements in the hashtable can be updated by passing a key in the indexer. We can retrieve the value this way and also update the value.

For example, given hashtable cities. If one of the keys is IN and we want to update the value of this key, we can write,

Cities[“IN”] = “Mumbai”;

This will update the existing value for the key.

But note that since Hashtable is a non-generic collection, we must type the case the values if the values are being retrieved.

Example

Let’s consider the following example wherein we update the elements of the hashtable.

using System;using System.Collections;class MyHashTable { public static void Main() { // Create a Hashtable Hashtable cities = new Hashtable(); // Add elements to the Hashtable cities.Add("UK", "London, Liverpool, Bristol"); cities.Add("USA", "Los Angeles, Boston, Washington"); cities.Add("India", "New Delhi, Mumbai, Kolkata"); //print original hashtabel Console.WriteLine("Hashtable items:"); foreach(DictionaryEntry entry in cities){ Console.WriteLine("{0} => {1} ", entry.Key, entry.Value); } //update hashtable with new values for US and UK cities["UK"] = "Manchester, Birmingham, Leeds"; cities["USA"] = "Chicago, New York, Texas"; //print updated hashtable Console.WriteLine("
Hashtable items after Updation:"); foreach(DictionaryEntry entry in cities){ Console.WriteLine("{0} ==> {1} ", entry.Key, entry.Value); } }}

In this program, we have a ‘cities’ hashtable. Each key (city code) is mapped to more than one value. First, we display the original contents of the hashtable. Then we update the values for two keys, USA and UK. Againwe display the updated hashtable.

Output

This program displays the following output.

Hashtable items:USA => Los Angeles, Boston, Washington India => New Delhi, Mumbai, Kolkata UK => London, Liverpool, Bristol Hashtable items after Updation:USA ==> Chicago, New York, Texas India ==> New Delhi, Mumbai, Kolkata UK ==> Manchester, Birmingham, Leeds 

Note that we didn’t update the values for Key = India. The rest of the key values were updated and they are displayed in the second set in the output.

Example

Let’s consider another example. Here instead of adding values using Add method, we use the initializer to initialize the hashtable object.

using System;using System.Collections;class MyHashTable { public static void Main() { // Create a Hashtable Hashtable phonetics = new Hashtable() { {"A", "Apple"}, {"B", "Bat"}, {"C", "Cat"} }; //print original hashtabel Console.WriteLine("Hashtable items:"); foreach(DictionaryEntry entry in phonetics) { Console.WriteLine("{0} => {1} ", entry.Key, entry.Value); } //update hashtable with new values for all keys phonetics["A"] = "Ant, Anchor, Arm"; phonetics["B"] = "Ball, Baby, Beam"; phonetics["C"] = "Car, Cake, Camel"; //print updated hashtable Console.WriteLine("
Hashtable items after Updation:"); foreach(DictionaryEntry entry in phonetics) { Console.WriteLine("{0} ==> {1} ", entry.Key, entry.Value); } }}

Here we are using a phonetics hashtable. First, we have initialized the hashtable object with one value for each key. Then we update each key with multiple values.

Output

This program generates the following output.

Hashtable items:A => Apple B => Bat C => Cat Hashtable items after Updation:A ==> Ant, Anchor, Arm B ==> Ball, Baby, Beam C ==> Car, Cake, Camel 

We can see the different outputs before updation and after updation.

In this article, we have discussed storing and updating the values in hashtables. We can store values in the hashtable by initializing the hashtable object during declaration using a new operator. We can also store objects in the hashtable using Add method. For updating the values in the hashtable, we can access the key of the element and then update its value using the assignment operator.

Shilpa Nadkarni

Updated on: 06-Jan-2023

1K+ Views

  • Related Articles
  • How to Get Hashtable Elements as Sorted Array?
  • How to Use Enumeration to Display Elements of Hashtable in Java?
  • How to store elements in numeric order for Listview in Android?
  • Copying the Hashtable elements to an Array Instance in C#
  • Remove all elements from the Hashtable in C#
  • How to Convert Hashtable to String?
  • How to use Hashtable splatting in PowerShell?
  • How to Convert Hashtable into an Array?
  • How to Iterate Through HashTable in Java?
  • How to convert Dictionary to Hashtable in PowerShell?
  • How to store data to DOM?
  • How to Create a HashTable Collection in C#?
  • Update elements inside an array in MongoDB?
  • Check if a Hashtable is equal to another Hashtable in C#
  • C# Program to Replace Items in One Hashtable with Another Hashtable
Kickstart Your Career

Get certified by completing the course

Get Started

How to store/update Hashtable Elements? (2)

Advertisem*nts

How to store/update Hashtable Elements? (2024)
Top Articles
2023 Mining Technology Trends for Safer & Smarter Operations | Inpixon
The best animals for your small farm
Whas Golf Card
Joi Databas
Restaurer Triple Vitrage
Hk Jockey Club Result
Sissy Hypno Gif
Palace Pizza Joplin
Top Golf 3000 Clubs
Hover Racer Drive Watchdocumentaries
What is the surrender charge on life insurance?
Items/Tm/Hm cheats for Pokemon FireRed on GBA
Used Wood Cook Stoves For Sale Craigslist
Methodist Laborworkx
Los Angeles Craigs List
Lax Arrivals Volaris
Are They Not Beautiful Wowhead
Committees Of Correspondence | Encyclopedia.com
Toy Story 3 Animation Screencaps
Craigslist Appomattox Va
Craigslist Lakeville Ma
Selfservice Bright Lending
Homeaccess.stopandshop
Air Quality Index Endicott Ny
Cookie Clicker Advanced Method Unblocked
Defending The Broken Isles
Breckiehill Shower Cucumber
Is Henry Dicarlo Leaving Ktla
They Cloned Tyrone Showtimes Near Showbiz Cinemas - Kingwood
Remnants of Filth: Yuwu (Novel) Vol. 4
John Deere 44 Snowblower Parts Manual
2021 Tesla Model 3 Standard Range Pl electric for sale - Portland, OR - craigslist
Ezstub Cross Country
Ridge Culver Wegmans Pharmacy
Calculator Souo
Fandango Pocatello
Strange World Showtimes Near Atlas Cinemas Great Lakes Stadium 16
Ket2 Schedule
RALEY MEDICAL | Oklahoma Department of Rehabilitation Services
Felix Mallard Lpsg
8 Ball Pool Unblocked Cool Math Games
Engr 2300 Osu
Best Restaurants West Bend
Ladyva Is She Married
Ds Cuts Saugus
Craigslist Mendocino
Large Pawn Shops Near Me
Rocket League Tracker: A useful tool for every player
Canonnier Beachcomber Golf Resort & Spa (Pointe aux Canonniers): Alle Infos zum Hotel
York Racecourse | Racecourses.net
Festival Gas Rewards Log In
Ippa 番号
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 5592

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.