Home > Backend Development > C#.Net Tutorial > How to add items to a hash table collection in C#

How to add items to a hash table collection in C#

王林
Release: 2023-09-12 09:49:02
forward
1119 people have browsed it

如何在 C# 中向哈希表集合添加项目

We have discussed the basics of hash tables. Hash table collections in C# are used to store key-value pairs, where each key-value pair is organized based on the hash code of the key. The hash code is calculated using a hash code function. Internally, hash tables use buckets to store data. A bucket is nothing more than a set of virtual elements in a hash table. A hash code is associated with each bucket.

From a programming perspective, a hash table is similar to a dictionary object, but unlike a dictionary object, a hash table can store objects of different data types. In terms of performance, hash tables exhibit lower performance because the data elements of hash tables are objects. Therefore, in order to store and retrieve values ​​from a hash table, boxing and unboxing of objects must be performed.

In this article, we will discuss how to add items to a hash table collection.

How to add items to a hash table collection?

The

hashtable collection in C# is implemented using the hashtable class. This class provides various methods to perform different operations on the hash table. One of the methods is Add().

The Add() method of the hash table class is used to add elements with the specified key and its corresponding value in the hash table. When adding key-value pairs to a hash table, we should ensure that the keys are not duplicated or empty because hash tables only allow non-empty and unique keys.

In C#'s hash table collection, we can have key/value pair elements of different data types.

Now let's move on to the Add() method.

The general prototype of the Add() method of the hash table collection is given below.

grammar

public virtual void Add(object key, object value);
Copy after login

parameter

  • Key - The specified key (type System.Object) of the element being added. Should be non-empty.

  • Value - The specified value of the element (type System.Object) This value can be null.

Exception: This method throws the following exception.

  • ArgumentNullException − When the key is null.

  • ArgumentException − An element with the same key already exists.

  • NotSupportedException − The hash table has a fixed size or is read-only.

If we have a hash table object declared as follows -

Hashtable hshTable = new Hashtable();
Copy after login

We can then add an element to the hash table object using the Add() method as shown below -

hshTable.Add("msg", "charVal");
Copy after login

Since hash tables allow elements of mixed data types, we can also add numerical values ​​in the same hash table -

hshTable.Add(1, 2022);
Copy after login

In addition to using the Add() method, we can also directly assign values ​​to the hash table. For example, to add an element with key = 2, we can simply write,

hshTable[3] = "three";
Copy after login

The above statement will create a key-value pair (3, "three") in the hash table.

Programming example of adding items to a hash table collection

The following program demonstrates how to use the Add() method to build a hash table of different elements.

Example 1

using System;
using System.Collections;
class Program {
   static void Main(string[] args) {
      Hashtable mixedHashTable = new Hashtable();
      //add method
      mixedHashTable.Add("msg", "Collection");
      mixedHashTable.Add("site", "HashTable");
      mixedHashTable.Add(1, 3.14);
      mixedHashTable.Add(2, null);

      //assign value to the key
      mixedHashTable[3] = "Tutorial";

      // Add method throws an exception if the key already exists in //hashtable
      try {
         mixedHashTable.Add(2, 750);
      } catch {
         Console.WriteLine("Hashtable already has an element with Key = '2'.");
      }
      Console.WriteLine("*********HashTable Elements********");
      // It will return elements as Key-Value Pair.
      foreach (DictionaryEntry elem in mixedHashTable) {
         Console.WriteLine("Key = {0}, Value = {1}", elem.Key, elem.Value);
      }
      Console.ReadLine();
   }
}
Copy after login

The above program first creates a hash table object using the default constructor. It then adds the different elements to the hash table using the Add() method. We can also add elements to the hash table by direct assignment. The above program adds key-value pairs of different data types to a hash table. Then use an iterator to display the elements of the hash table one by one.

Output

The output of the above example is as follows -

Hashtable already has an element with Key = '2'.
*********HashTable Elements********
Key = 2, Value = 
Key = msg, Value = Collection
Key = 3, Value = Tutorial
Key = site, Value = HashTable
Key = 1, Value = 3.14
Copy after login

The output shows all the key-value pairs we added to the hash table.

Let’s give another example of adding elements to a hash table. The procedure is as follows.

Example 2

using System;
using System.Collections;
class hTable {
   // Driver code
   public static void Main() {
      // Creating a Hashtable
      Hashtable strHashTable = new Hashtable();

      // Adding elements in Hashtable
      strHashTable.Add("4", "Even Number");
      strHashTable.Add("9", "Odd Number");
      strHashTable.Add("5", "Odd and Prime Number");
      strHashTable.Add("2", "Even and Prime Number");

      // Get a collection of the keys.
      ICollection c = strHashTable.Keys;

      // Displaying the hashtable contents
      Console.WriteLine("=========Contents of the Hashtable=========");
      foreach(string str in c)
         Console.WriteLine(str + ": " + strHashTable[str]);
   }
}
Copy after login

In this program, we add a value of string type. We add the value using the Add() method and then retrieve the set of keys in the hash table. We then use a foreach loop to iterate through this set of keys and display each key and its corresponding value.

Output

The generated output is as follows -

=========Contents of the Hashtable=========
5: Odd and Prime Number
9: Odd Number
2: Even and Prime Number
4: Even Number
Copy after login

In this way, we can add items to the hashtable collection using the Add() method of the hashtable class.

We learned in this article how to add items to a hash table collection. In future articles, we will discuss more about Hashtable operations.

The above is the detailed content of How to add items to a hash table collection in C#. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template