Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/articles/c-sharp-tutorials/)
-   -   Bidirectional Hashtable (http://www.go4expert.com/articles/bidirectional-hashtable-t1466/)

shabbir 25Sep2006 13:14

Bidirectional Hashtable
 
1 Attachment(s)

Introduction



Sometimes you have data with a 1:1 relationship between the key and values and you need to put them into a Hashtable for easy retrieval and later realize you need to look up the keys from the values in the table. I came across such a problem for a combo box item displayed and actual value stored in the database and wrote the following class for would like to share the same with you. This article will be a step towards solving the problem.

Background



The solution is to have a hashtable which adds apart from key -> value pair also adds the value -> key pair to the hash table. This is not one of the better way of doing this but for me it is one of the best because I have some values that is displayed to user in a combo box and the aim of mine is to get the value based on the key selected as well pre-populate the combo-box with the value stored in the database. So I wrote the class to manage this. All you need to do is insert the class into your namespace and have it pointed to the BiDirHashtable instead of Hashtable. It has all the 15 constructors overloaded and so you will not run into problem about constructors not being defined.

Overridables



Overrides the Add method for adding an element to the Hashtable
Code: CSharp

public override void Add(object key, object value)
{
    base.Add(key, value);
    base.Add(value, key);
}

Adds the key -> value as well as value -> key combination to the Hashtable.

Sample code for adding to the hash tables
Code: CSharp

BiDirHashtable bdh = new BiDirHashtable();
bdh.Add("1", "Go4Expert");
bdh.Add("2", "G4EF");
bdh.Add("3", "MSN");
bdh.Add("4", "Google");
bdh.Add("5", "Yahoo");

Overrides the Remove method to remove an element from the hashtable
Code: CSharp

public override void Remove(object key)
{
    base.Remove(base[key]);
    base.Remove(key);
}

Removes the key -> value as well as value -> key pair. The order of removing is important. You should not be removing the key before the value as you will not be able to get the other object you want to remove.

Sample code for removing from the hash tables
Code: CSharp

BiDirHashtable bdh = new BiDirHashtable();
bdh.Add("1", "Go4Expert");
bdh.Add("2", "G4EF");
bdh.Add("3", "MSN");
bdh.Add("4", "Google");
bdh.Add("5", "Yahoo");

bdh.Remove("1");
bdh.Remove("MSN");
bdh.Remove("5");

Now the most important aspect of it is counter. It will not reflect the correct number of elements and so you should override the Count property.
Code: CSharp

public override int Count
{
    get
    {
        return base.Count / 2;
    }
}

I have attached the BiDirHashtable class for you to download.


All times are GMT +5.5. The time now is 06:56.