C# hashtable


Release date:2023-09-06 Update date:2023-10-13 Editor:admin View counts:256

Label:

C# hashtable

The Hashtable class represents a series of key/value pairs organized by key-based hash code. It uses keys to access elements in the collection.

When you use keys to access elements, a hash table is used, and you can identify a useful key value. Each item in the hash table has a key/value pair. Key is used to access items in the collection.

Methods and properties of the Hashtable class

The following table lists some common properties of Hashtable class:

Attribute

Description

Count

Gets the number of key-value pairs contained in Hashtable.

IsFixedSize

Gets a value indicating whether the Hashtable has a fixed size.

IsReadOnly

Gets a value indicating whether the Hashtable is read-only.

Item

Gets or sets the value associated with the specified key.

Keys

Gets an ICollection containing the keys in the Hashtable.

Values

Gets an ICollection that contains the value in the Hashtable.

The following table lists some common methods of Hashtable:

Serial number

Method name & description

1

Public virtual void Add (object key, object value); adds an element with thespecified key and value to Hashtable.

2

Public virtual void Clear (); removes all elements from the Hashtable.

3

Public virtual bool ContainsKey (object key); determines whether the Hashtable contains the specified key.

4

Public virtual bool ContainsValue (object value); determines whether the Hashtable contains the specified value.

5

Public virtual void Remove (object key); removes the element with the specified key from the Hashtable.

Example

The following example demonstrates the concept of a Hashtable:

Example

using System;
using System.Collections;
namespace CollectionsApplication
{
   class Program
   {
      static void Main(string[] args)
      {
         Hashtable ht = new Hashtable();
         ht.Add("001", "Zara Ali");
         ht.Add("002", "Abida Rehman");
         ht.Add("003", "Joe Holzner");
         ht.Add("004", "Mausam Benazir Nur");
         ht.Add("005", "M. Amlan");
         ht.Add("006", "M. Arif");
         ht.Add("007", "Ritesh Saikia");
         if (ht.ContainsValue("Nuha Ali"))
         {
            Console.WriteLine("This student name is already in the
list");
         }
         else
         {
            ht.Add("008", "Nuha Ali");
         }
         // Get a collection of keys
         ICollection key = ht.Keys;
         foreach (string k in key)
         {
            Console.WriteLine(k + ": " + ht[k]);
         }
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces the following results:

007: Ritesh Saikia
004: Mausam Benazir Nur
005: M. Amlan
008: Nuha Ali
002: Abida Rehman
003: Joe Holzner
001: Zara Ali
006: M. Arif

Powered by TorCMS (https://github.com/bukun/TorCMS).