Home > DeveloperSection > Articles > Working with HashTable in C# 2.0

Working with HashTable in C# 2.0


C# C# 
Ratings:
0 Comment(s)
 5250  View(s)
Rate this:

Working with HashTable in C# 2.0

We use an Hashtable when we want to store information based on Key/Value pairs. For example, the role number of a students and the score in an exam. In other programmes, Hashtables are known as associative arrays.

Hashtable students = new Hashtable();

This creates a new object called students. It's going to be an Hashtable object.

There are two ways we can add data into Hashtable. Like this:

students[101] = 87;
students[102] = "No Score";
students[103] = 64;
students[104] = 79;

Or like this:

students.Add(101, 87);
students.Add(102, "No Score";);
students.Add(103, 64);
students.Add(104, 79);

The first method uses a pair of square brackets:

students[101] = 87;

In between the square brackets, we type what's known as the Key. So this particular entry in the Hashtable is called 101. After an equals sign, we then type the Value that this Key will hold. Notice that three of the entries are number values, and one (102) is text.

The second way to store values in an Hashtable is to use the Add Method:

students.Add(101, 87);

In between the round brackets of Add( ), we first type the Key name. After a comma, we type the Value for that Key.

There is a difference between the two. If we use the Add method, we can't have duplicate Key names. But we can if we use the square brackets. So this will get we an error:

students.Add(101, 87);
students.Add(101, 35);

But this won't:

students [101] = 87;
students[101] = 35;

Retrieving data from HashTable

Hashtable students = new Hashtable();

students[101] = 87;
students[102] = "No Score";
students[103] = 64;
students[104] = 79;

 

foreach (DictionaryEntry de in students)
{
listBox1.Items.Add("students: " + de.Key + " , Score: " + de.Value);
}

 

Before running the code, have a look at the foreach loop. Inside of the round brackets, we have this:

DictionaryEntry de

This sets up a variable called de. But note the type of variable it is: a DictionaryEntry. C# uses an object of this type when using the foreach loop with Hashtables. That's because it automatically returns both the Key and the Value.

Notice, too, what we have between the round brackets of the listbox's Add method:

"students: " + de.Key + " , Score: " + de.Value

The red bold are the important parts. After typing the name of wer variable (de, for us) and a full stop, the IntelliSense list will appear. Key is a property that returns the name of wer Key, and Value is a property that returns whatever we placed inside of that Key.

Note: - Use namespace “System.Collections” for HashTable.

/// <summary>

        /// Add items in Hastable

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnAdd_Click(object sender, EventArgs e)

        {

            try

            {

                //Add new item in HashTable object

                student.Add(txtRollNo.Text,txtScore.Text);

            }

            catch (Exception ex)

            {

                //Display exception message

                MessageBox.Show(ex.Message);

            }

        }

 

        /// <summary>

        /// Display stored items in ListBox from HasTable

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnDisplay_Click(object sender, EventArgs e)

        {

            //clear the old list items form HasTable object

            lbDisplay.Items.Clear();

            //retrive record from HasTable object

            foreach (DictionaryEntry de in student)

            {

                //display HasTable items in listbox

                lbDisplay.Items.Add("Roll No." + de.Key + " \t Score" + de.Value);

            }

        }

 

Notice that the list of items has been sorted automatically. But the sort is done on the Keys, not on the Values.

But just like the ArrayList, you can Add new items, and remove old ones. To Remove an item, you do it like this:

students.Remove(101);

So you refer to the Key name, and not the Value, when you use the Remove method.

 


Don't want to miss updates? Please click the below button!

Follow MindStick