C# Hashtable
The Hashtable class represents a collection of key/value pairs organized based on the hash code of the key. It uses the key to access the elements in the collection.
When you use a key to access elements, you use a hashtable, and you can identify a useful key value. Each item in the hashtable has a key/value pair. The key is used to access the item in the collection.
Methods and Properties of the Hashtable Class
The following table lists some common properties of the Hashtable class:
Property | Description |
---|---|
Count | Gets the number of key/value pairs contained in the 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 containing the values in the Hashtable. |
The following table lists some common methods of the Hashtable class:
No. | Method & Description |
---|---|
1 | public virtual void Add(<br> object key,<br> object value<br>); <br>Adds an element with the specified key and value into the Hashtable. |
2 | public virtual void Clear(); <br>Removes all elements from the Hashtable. |
3 | public virtual bool ContainsKey(<br> object key<br>); <br>Determines whether the Hashtable contains a specific key. |
4 | public virtual bool ContainsValue(<br> object value<br>); <br>Determines whether the Hashtable contains a specific value. |
5 | public virtual void Remove(<br> object key<br>); <br>Removes the element with the specified key from the Hashtable. |
Example
The following example demonstrates the concept of a hashtable:
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 the 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 result:
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