Title: Use a Dictionary to store and retrieve items in C#
This example demonstrates a Dictionary. A Dictionary is basically a strongly typed Hashtable.
A Hashtable stores key/value pairs in a way that makes looking up values extremely fast. For example, suppose you have an employee database that uses EmployeeId values to look up Employee object. If you use a Hashtable to store the values, you can find a particular employee very quickly.
The problem with the Hashtable class is that it works with the non-specific object class. That means your code needs to cast items from the object class to a specific class (for example, Employee) when you get an item from the Hashtable.
It also means the Hashtable doesn't perform type checking so your code could add anything anything to the Employees Hashtable. It could add Employee objects as intended, or it could accidentally add Customer, Invoice, or DogFood objects to the Hashtable.
The Dictionary class provides features similar to a Hashtable but it is a generic class so it is strongly typed. That means your code doesn't need to convert from generic objects into specific types. It also means the Dictionary ensures that your code passes the right kinds of objects to it.
The following code declares and initializes the Dictionary.
// The dictionary.
private Dictionary Words = new Dictionary();
The Dictionary class's type parameters give the types of the keys and values stored in the Dictionary. In this example, they are both strings.
If you enter a key and value and click the Add button, the program uses the following code to add the value to the Dictionary.
// Add a value to the dictionary.
private void btnAdd_Click(object sender, EventArgs e)
{
if (Words.ContainsKey(txtKey.Text))
{
MessageBox.Show(
"The dictionary already contains this key.");
}
else
{
Words.Add(txtKey.Text, txtValue.Text);
txtKey.Clear();
txtValue.Clear();
txtKey.Focus();
ListValues();
}
}
A Dictionary can hold only one value for a given key and throws an exception if you try to add an entry with an existing key. To protect itself from that exception, the code uses the Dictionary object's ContainsKey method to see if the key is already in the Dictionary. If the key is already present, the program displays a message. If the key is not present, the program calls the object's Add method, passing it the new key and value.
If you enter a key and click the Find button, the following code displays the corresponding value in the Dictionary.
// Look up a value.
private void btnFind_Click(object sender, EventArgs e)
{
if (!Words.ContainsKey(txtKey.Text))
{
txtValue.Text = "";
}
else
{
txtValue.Text = Words[txtKey.Text];
}
}
If you try to use a value for a key that isn't present in a Dictionary, the Dictionary again throws an exception. To protect itself, this code first uses the Dictionary object's ContainsKey method to see if the key is present. If the key is missing, the code displays a message. If the key is present, the code displays the corresponding value.
If you enter a key and click the Delete button, the following code executes.
// Remove an item from the dictionary.
private void btnDelete_Click(object sender, EventArgs e)
{
if (!Words.ContainsKey(txtKey.Text))
{
MessageBox.Show("Item not found");
}
else
{
Words.Remove(txtKey.Text);
ListValues();
}
}
If you try to delete a value with a key that isn't in the Dictionary, the Dictionary once again throws an exception so, again, this code uses the Contains method to protect itself. If the key is not in the Dictionary, the code displays a message. If the key is in the Dictionary, the code deletes it and its value.
Whenever the program changes the contents of the Dictionary, it calls the following ListValues method to display all of the keys and their values.
// List the dictionary's current values.
private void ListValues()
{
lstValues.Items.Clear();
foreach (string key in Words.Keys)
{
lstValues.Items.Add(key + ": " + Words[key]);
}
}
The code loops through the Dictionary object's keys. For each key, it adds the key plus the corresponding value to the ListBox named lstValues.
Note that by default the Dictionary class is case-sensitive. That means you could have an entry with key "ID 123" and a second entry with key "Id 123." In my next post I'll explain an easy way to make a case-insensitive Dictionary.
Download the example to experiment with it and to see additional details.
|