How to use a Hashtable in C#.
Creating a Hashtable
The following code creates a Hashtable:
private Hashtable hsTable = new Hashtable();
Adding Items to a Hashtable
Add method of Hashtable is used to add items to the hashtable. The
method has index and value parameters.
The following code adds items to hashtable.
hsTable .Add("Game1", "Cricket");
hsTable.Add("Game2", "Football");
hsTable.Add("Game3", "Badminton");
hsTable.Add("Game3", "Basketball");
hsTable.Add("Game3", "Tennis");
Retrieving an Item Value from Hashtable
The following code returns the value of "Cricket" key:
string name = hsTable ["Cricket "].ToString();
Removing Items from a Hashtable
The Remove method removes an item from a Hashtable.
The following code removes item with index "Cricket" from the hashtable:
hsTable.Remove("Cricket");
Looking through all Items of a Hashtable
The following code loops through all items of a hashtable and reads the values.
IDictionaryEnumerator en = hsTable.GetEnumerator(); while (en.MoveNext())
{
string str = en.Value.ToString();
}
Leave Comment