About a week ago I began talking about collections in C#, and discussed two special cases, the Stack and the Queue. Another group of specialized collection classes are dictionaries. Dictionaries operate off of a key / value system, where you lookup your information, your value, based on a key you create. The key can be a string, number or other type of data, but it must be unique within the dictionary. Just like in your traditional printed dictionary, you can’t have two entries for the same key.
The most basic type of Dictionary is the Hashtable. The hashtable has the basic functionality for putting entries into the dictionary collection, getting a value based on a key, looping through them, and updating or removing them.
Getting data into the hashtable is pretty easy. First make sure to include a using reference to System.Collections, then simply create a hashtable variable, and finally call the Add method, passing in the key and value.
Hashtable myHash = new Hashtable();
myHash.Add(“ArcaneCode”, “arcanecode.wordpress.com”);
To read or update the data stored in the value, you can treat the hashtable as if it were a simple array, using the key where you’d normally put the index.
Console.WriteLine(myHash[“ArcaneCode”]);
myHash[“ArcaneCode”] = “Here I’ve changed the value.”;
Console.WriteLine(myHash[“ArcaneCode”]);
Console.Read();
Hashtables are great for storing data where you have a good primary key you can quickly reference things by. In our example, I’ve stored strings as the value part of the key / value pair, but you can use any type of object for the value, including classes you create.
The examples so far assume you will always want to retrieve a single item out of your hashtable. However, we all know there are times when you will want to iterate over the entire collection. To do this, it’s necessary to understand how your key / value pair is storied.
In keeping with the spirit of OOP, what is actually stored in the hashtable collection is another object of type DictionaryEntry. The dictionary entry object has two essential properties, the Key and the Value, both of which are the generic object type. Here’s an example of how to loop over the myHash collection.
// Clear out the previous items
myHash.Clear();
// Now add some new items.
// Note we use an int as the key this time.
myHash.Add(1, “Item one”);
myHash.Add(2, “Item two”);
myHash.Add(3, “Item three”);
// Loop over the list, writing out the value
foreach (DictionaryEntry myEntry in myHash)
{
Console.WriteLine(myEntry.Value);
}
Console.Read(); // Wait for user to press a key
Note we cycle through a list of DictionaryEntry objects, and each time through get the Value property. If we wanted to get the key, it would be a simple matter of replacing the Value property call with a call to Key.
If you are in a situation where you are not sure of the data types being used in the keys or the values, you should append a .ToString() after a reference to the Key or Value so as not to generate run time errors when displaying. In the above example, we’d have needed to use Console.WriteLine(myEntry.Key.ToString()); since our keys were integers (1, 2, and 3).
As you can see, the hashtable makes it easy to look up values when you have a specific key, yet at the same time is still flexible enough to allow you to iterate over your entire collection when you need to.
Hi, your homepage looks really good and gives great information! Anyway, nice job. Keep it up please!!! My best wishes to you all!
What are the size limits both in terms of key-length and in terms of # entries before it bogs down on add/retrieve?
From what I have been able to determine David, the best answer I can find is “it depends”.
I know, it seems like it’s always the answer, but in part it’s tied to your machine’s hardware. Amount of RAM, CPU speed, single vs. dual core, etc.
The best advice I can give is to do some trial tests at what you expect the upper bounds of your hashtable to be with realistic data in it, and see what happens.
Arcane
hi,
I need dictionary code , with c# and sql server 2000.
please help me.
I want to fetch the Hashtable items in the same sequence in which I added in it using foreach loop with the help of DictionaryEntry. How it can be done.
You want an OrderedDictionary() for that.
http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx
Hi, i have a problem. The data that i get using the hastable is gettin lost when i try to bind it to the combo box. Plss help me solve the issue.
Thanks for the help tips in your website. just the information i need! =)
using ?
usign System.Collections;
Hello
When i am using the Hashtable them i am getting this error.
Error Description: Item has already been added. Key in dictionary: ‘ProjectList’ Key being added: ‘ProjectList’
can you please tell me where i am wrong ?
Thanks
Vanit
Vanit, a hashtable requires that each key be unique. Once you add a key to a hashtable, you cannot add it again. You CAN update the value, as you see in his first code example, he changes the value at the key ArcaneCode to “Here I’ve changed the value.”
You can do this:
hash.Add(“myKey”,1);
hash[“myKey”] = 2;
But you can’t do this:
hash.Add(“myKey”,1);
hash.Add(“myKey”,2);