Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This article introduces how to use the HashTable collection in Visual C#.
Original product version: Visual C#
Original KB number: 309357
Summary
Because hashing eliminates the need for costly searching of data to retrieve the data, you can use hashing to efficiently retrieve data. Hashing uses the value of the key itself to locate of the data.
The Base Class Libraries offer a HashTable class that is defined in the System.Collections namespace so that you are not required to code your own hash tables.
Steps to build the sample
A HashTable collection stores a (Key, Value) pair and uses the Key to hash and obtain the storage location. The Key is immutable and cannot have duplicate entries in the HashTable. This sample uses several instances of a simple Person class to store in a HashTable. The last name is used as the Key.
Open Microsoft Visual Studio, and create a Windows Forms Application project in Visual C#. Form1 is added to the project by default.
In Solution Explorer, right-click the project name, point to Add, and then select Class to add a class module.
Class1is added to the project by default.Replace any code in the
Class1module with the following code:public class Person { public string Fname, Lname;d public Person (string FirstName, string LastName) { Fname = FirstName; Lname = LastName; } public override string ToString () { return Fname + " " + Lname; } }The
Personclass has one constructor that takes theFirstNameandLastNameparameters and assigns these parameters to the local variables. TheToStringfunction overridesToStringfrom theObjectclass to returnFnameandLnameconcatenated together.Create a form-level
Hashtableobject, and declare three variables of typePerson. Add the following code to theForm1class:<?xm-deletion_mark author="v-bobbid" time="20080711T172143-0800" data="private Hashtable MyTable = new Hashtable(); //For simplicity, create three Person objects to add to the HashTable collection. Person Person1,Person2,Person3; "?> <?xm-insertion_mark_start author="v-bobbid" time="20080711T172143-0800"?> System.Collections.Hashtable MyTable = new System.Collections.Hashtable(); //For simplicity, create three Person objects to add to the HashTable collection. Person Person1,Person2,Person3; <?xm-insertion_mark_end?>In the following steps, use the
Addmethod of theHashtableobject to add threePersonobjects to theHashtablein atry-catchblock. Thetry-catchblock catches the exception and displays a message if duplicate keys exist:Place a Button control on Form1, and change the Text property to Add Items.
Double-click the button to open its Code window, and paste the following code in the
Button1_Clickevent:Person1 = new Person("David", "Burris"); Person2 = new Person("Johnny", "Carrol"); Person3 = new Person("Ji", "Jihuang"); //The Add method takes Key as the first parameter and Value as the second parameter. try { MyTable.Add(Person1.Lname, Person1); MyTable.Add(Person2.Lname, Person2); MyTable.Add(Person3.Lname, Person3); } catch (ArgumentException ae) { MessageBox.Show("Duplicate Key"); MessageBox.Show(ae.Message); }
The
Hashtableobject provides an indexer. In the following steps, index with theKeyto access the value that is stored at the hashed location:Add a Button control to Form1, and change the Name property to Get Items.
Double-click the button, and paste the following code in the
Button2_Clickevent://Use the indexer of the Hashtable class to retrieve your objects. The indexer takes //Key as a parameter and accesses it with the Hashed location. try { MessageBox.Show(MyTable[Person1.Lname].ToString()); MessageBox.Show(MyTable[Person2.Lname].ToString()); MessageBox.Show(MyTable[Person3.Lname].ToString()); } catch (NullReferenceException ex) { MessageBox.Show("Key not in Hashtable"); MessageBox.Show(ex.Message); }
In the following steps, use the
Removemethod to remove a single item from theHashTablecollection:Add a Button control to Form1, and change the Text property to Remove Item.
Double-click the button, and paste the following code in the
Button3_Clickevent:<?xm-deletion_mark author="v-bobbid" time="20080711T173011-0800" data="if (MyTable.Count == 0) { MessageBox.Show("There are no items in HashTable"); } else { MessageBox.Show("The count before removing an Item is" + " " + MyTable.Count); MessageBox.Show("Removing value stored at key value (Burris)"); Remove the object that is stored at the Key value Person1.Lname. MyTable.Remove(Person1.Lname); } "?> <?xm-insertion_mark_start author="v-bobbid" time="20080711T173011-0800"?>if (MyTable.Count == 0) { MessageBox.Show("There are no items in HashTable"); } else { MessageBox.Show("The count before removing an Item is" + " " + MyTable.Count); MessageBox.Show("Removing value stored at key value (Burris)"); // Remove the object that is stored at the Key value Person1.Lname. MyTable.Remove(Person1.Lname); } <?xm-insertion_mark_end?>
In the following steps, enumerate the items that are stored in the
HashTablecollection:Add a Button control to Form1, and change the Text property to Enumerate.
Double-click the button, and paste the following code in the
Button4_Clickevent:<?xm-deletion_mark author="v-bobbid" time="20080711T174252-0800" data="IDictionaryEnumerator Enumerator; if (MyTable.Count == 0) MessageBox.Show("The hashtable is empty"); else { MessageBox.Show("Enumerating through the Hashtable collection"); Enumerator = MyTable.GetEnumerator(); while (Enumerator.MoveNext()) { MessageBox.Show(Enumerator.Value.ToString()); } } ICollection MyKeys; if (MyTable.Count == 0) MessageBox.Show("The hashtable is empty"); else { MessageBox.Show("Accessing keys property to return keys collection"); MyKeys = MyTable.Keys; foreach (object Key in MyKeys) { MessageBox.Show(Key.ToString()); } } "?> <?xm-insertion_mark_start author="v-bobbid" time="20080711T174252-0800"?> System.Collections.IDictionaryEnumerator Enumerator; if (MyTable.Count == 0) MessageBox.Show("The hashtable is empty"); else { MessageBox.Show("Enumerating through the Hashtable collection"); Enumerator = MyTable.GetEnumerator(); while (Enumerator.MoveNext()) { MessageBox.Show(Enumerator.Value.ToString()); } } System.Collections.ICollection MyKeys; if (MyTable.Count == 0) MessageBox.Show("The hashtable is empty"); else { MessageBox.Show("Accessing keys property to return keys collection"); MyKeys = MyTable.Keys; foreach (object Key in MyKeys) { MessageBox.Show(Key.ToString()); } } <?xm-insertion_mark_end?>This code declares a variable of type
IDictionaryEnumeratorand calls theGetEnumeratormethod of theHashTablecollection. With theEnumeratorreturned, the code enumerates through the items in the collection and uses theKeysmethod of theHashTableto enumerate through the keys.
In the following steps, use the
Clearmethod to clear theHashTable:Add a Button control to Form1, and change the Text property to Clear.
Double-click the button, and paste the following code in the
Button5_Clickevent:MyTable.Clear(); MessageBox.Show("HashTable is now empty");
Follow these steps to build and run the application:
- Select Add Items. Three
Personobjects are added to theHashTablecollection. - Select Get Items. The indexer obtains the items in the
HashTablecollection. The three newly added items are displayed. - Select Remove Item. The item at the
Burriskey location is deleted. - Select Enumerate.
IDictionaryEnumeratorenumerates through the items in theHashTablecollection, and theKeysproperty of theHashTablereturns a Keys Collection. - Select Clear. All the items are cleared from the
HashTablecollection.
- Select Add Items. Three
Note
The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious. No association with any real company, organization, product, domain name, email address, logo, person, places, or events is intended or should be inferred.