HashTable class:-
- The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. It uses the key to access the elements in the collection.
- A hash table is used when you need to access elements by using key, and you can identify a useful key value.
- Each item in the hash table has a key/value pair. The key is used to access the items in the collection.
Methods and Properties of HashTable class:-
Methods of HashTable class:-
Sr.No. | Method |
---|---|
1 | public virtual void Add(object key, object value); Adds an element with the specified key and value into the Hashtable. |
2 | public virtual void Clear(); Removes all elements from the Hashtable. |
3 | public virtual bool ContainsKey(object key); Determines whether the Hashtable contains a specific key. |
4 | public virtual bool ContainsValue(object value); Determines whether the Hashtable contains a specific value. |
5 | public virtual void Remove(object key); Removes the element with the specified key from the Hashtable. |
Properties of HashTable class:-
Property | Description |
---|---|
Count | Gets the number of key-and-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. |
Hashtable Example:-
using System; using System.Collections; class HashTableDemo { public HashTableDemo() { Console.WriteLine("This is hash table demo::\n"); } public void Show() { Hashtable ht = new Hashtable(); ht.Add("001", "Santosh kumar singh"); ht.Add("002", "Gagan"); ht.Add("003", "Manorma arya"); ht.Add("004", "Reena kumari"); ht.Add("005", "Anjanee kumar singh"); ht.Add("006", "Pramod kumar sah"); ht.Add("007", "Laxmi Pati Ojha"); ht.Add("008", "Chandan kumar"); if (ht.ContainsValue("Rajeev kumar")) { Console.WriteLine("This student name is already in the list"); } else { ht.Add("009", "Rajeev kumar"); } // Get a collection of the keys. ICollection key = ht.Keys; foreach (string k in key) { Console.WriteLine(k + ": " + ht[k]); } } } class Test { static void Main(string[] args) { HashTableDemo objHT = new HashTableDemo(); objHT.Show(); Console.ReadLine(); } }