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
Guide to Brokerage Fees | The Motley Fool
6 Tips To Fix Syncing Issues in Microsoft OneDrive
Knoxville Tennessee White Pages
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Skamania Lodge Groupon
Summit County Juvenile Court
Farmers Branch Isd Calendar
Monticello Culver's Flavor Of The Day
Weather In Moon Township 10 Days
Locate Td Bank Near Me
Www.paystubportal.com/7-11 Login
Lima Crime Stoppers
Goldsboro Daily News Obituaries
Think Up Elar Level 5 Answer Key Pdf
History of Osceola County
De beste uitvaartdiensten die goede rituele diensten aanbieden voor de laatste rituelen
Race Karts For Sale Near Me
Energy Healing Conference Utah
Breckie Hill Mega Link
Theater X Orange Heights Florida
The Old Way Showtimes Near Regency Theatres Granada Hills
Governor Brown Signs Legislation Supporting California Legislative Women's Caucus Priorities
THE FINALS Best Settings and Options Guide
Wiseloan Login
Lexus Credit Card Login
Idle Skilling Ascension
Publix Near 12401 International Drive
Pacman Video Guatemala
Sam's Club Near Wisconsin Dells
Publix Daily Soup Menu
Rock Salt Font Free by Sideshow » Font Squirrel
Dreamcargiveaways
Boondock Eddie's Menu
EST to IST Converter - Time Zone Tool
Goodwill Houston Select Stores Photos
oklahoma city community "puppies" - craigslist
Marie Peppers Chronic Care Management
Honda Ruckus Fuse Box Diagram
What Does Code 898 Mean On Irs Transcript
Bcy Testing Solution Columbia Sc
Entry of the Globbots - 20th Century Electro​-​Synthesis, Avant Garde & Experimental Music 02;31,​07 - Volume II, by Various
5A Division 1 Playoff Bracket
FREE - Divitarot.com - Tarot Denis Lapierre - Free divinatory tarot - Your divinatory tarot - Your future according to the cards! - Official website of Denis Lapierre - LIVE TAROT - Online Free Tarot cards reading - TAROT - Your free online latin tarot re
Linkbuilding uitbesteden
Craigslist/Nashville
Top 1,000 Girl Names for Your Baby Girl in 2024 | Pampers
What is 'Breaking Bad' star Aaron Paul's Net Worth?
Ts In Baton Rouge
Ups Customer Center Locations
Minute Clinic Mooresville Nc
Helpers Needed At Once Bug Fables
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.