
- 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
How to store/update Hashtable Elements?
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. Again we 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.
- Related Articles
- How to Get Hashtable Elements as Sorted Array?
- 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 convert Dictionary to Hashtable in PowerShell?
- How to store data to DOM?
- Program to update elements in a given range in Python
- Update elements inside an array in MongoDB?
- How to Create a HashTable Collection in C#?
- How to Add Items to Hashtable Collection in C#
- Check if a Hashtable is equal to another Hashtable in C#
- C# Program to Replace Items in One Hashtable with Another Hashtable
