A C# Hashtable represents a collection in which objects are stored and retrieved using a key.
Each key in a Hashtable has a hash code using which the objects in a Hashtable are organized.
Create a Hashtable in C#
A Hashtable can be created using the below code:
Hashtable shoppingCart = new Hashtable();
Add items to a C# Hashtable
To add items to a Hashtable Add method is used. In the below example a key called as Camera with value 3 is added to the Hashtable shoppingCart.
shoppingCart.Add("Camera", 3);
Every item in a Hashtable has a unique key and an associated value. A Hashtable is a collection of such key/value pairs. Each of these items is a type of DictionaryEntry object. |
Below three unique keys are added to a Hashtable. The key name and the associated value is then displayed using a foreach loop.
Hashtable shoppingCart = new Hashtable(); shoppingCart.Add("Camera", 3); shoppingCart.Add("Computer", 2); shoppingCart.Add("Trouser", 5); foreach (DictionaryEntry item in shoppingCart) { Console.WriteLine("Key " + item.Key + " has value " + item.Value); }
Output:
Key Computer has value 2
Key Trouser has value 5
Key Camera has value 3
Key Computer has value 2
Key Trouser has value 5
Key Camera has value 3
Objects in a Hashtable can be null whereas the keys can't be. |
Remove items from C# Hashtable
To remove items from a Hashtable Remove method is used. In the below example the keyCamera is removed from the Hashtable shoppingCart.
shoppingCart.Remove("Camera", 3);
Removing a key also removes the associated value from a Hashtable. |
Methods and Properties of a C# Hashtable
Commonly used methods of a Hashtable are:
Method | Description |
---|---|
Add | Adds an item with a specific key and value to the Hashtable. |
Clear | Removes all items from the Hashtable. |
ContainKey | Checks if a specific key is present in a Hashtable. |
ContainsValue | Checks if a specific value is present in a Hashtable. |
GetHash | Gets the hash code associated with a key in a Hashtable. |
Remove | Removes a key and associated value from a Hashtable. |
Commonly used properties of a Hashtable are:
Property | Description |
---|---|
Count | Returns the number of items (Key/Value pairs) present in a Hashtable. |
IsReadOnly | Returns a boolean value which specifies whether a Hashtable is readonly or not. |
Item | Represents a key/value pair in a Hashtable. |
Keys | Returns a collection of all the keys present in a Hashtable. |
Values | Returns a collection of all the values present in a Hashtable. |
great
ReplyDelete