Page 1 of 1

Using The C# Hashtable Collection

#1 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1642
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Posted 22 February 2008 - 11:05 PM

Welcome to this tutorial on Using The C# Hashtable Collection. Hashing eliminates the resources normally needed for searching and retrieving data, since it uses the value of the key to find the requested data. We will be using the Hashtable Class, located in the System.Collections Namespace, thus eliminating the need to write our own Hashtable.

A Hashtable uses a (Key, Value) pair when storing the data, and uses the Key to find the requested data item. The Key value is immutable , and cant be duplicated in a Hashtable Class. In this tutorial we will create a Song Class, this class will be stored in a Hashtable, and we will use the name of the song for the key.


Creating The Class

For our Song Class, since it is going to be a simple class with but 2 Propeties, the only Namespace we need to Import is the System Namespace, this is the base of all other Namespaces, to import it do:


using System;




In this class we will have 2 Properties, one for the path to the song, one for the name of the song. As with all properties, we will need 2 private variables which will hold the values of our Properties for us. The variables are private as we don't want the user to be able to change their value directly.

Our 2 properties are Read/Write Properties, meaning they have a get and a set. The Get is used to retrieve the value of the property while the Set is used to set the value of the property:


#region Property Variables
/// <summary>
/// path property variable
/// </summary>
private string _path;

/// <summary>
/// name property variable
/// </summary>
private string _name;
#endregion

#region Class Properties
/// <summary>
/// property to hold the path to the song
/// </summary>
public string Path
{
    get { return _path; }
    set { _path = value; }
}

/// <summary>
/// property to hold the name of the song
/// </summary>
public string Name
{
    get { return _name; }
    set { _name = value; }
}
#endregion



NOTE: You will notice my code is seperated into sections with the #region...#endregion specifier. This allows me to divide similar sections of code, making it easier when searching through my code.

Next we will use a Constructor. In C# when you create a class as we are it is assumed by the Framework that a default Constructor is present, in fact if you do not add one, the default empty Constructor is assumed if you will. We are going to add a Constructor though, we will be setting the values of our property variables in our constructor, like so:


#region Constructor
/// <summary>
/// class constructor to set the values of our class properties
/// </summary>
/// <param name="path">path to the song</param>
/// <param name="name">name of the song</param>
public Song(string path, string name)
{
    //set the value of the path property
    _path = path;
    //set the value of the name property
    _name = name;
}
#endregion




We have one more method in our sample class. With this method we are going to override the default ToString Method. Doing this will allow us to return the full value of the song, path and name, when we get to retrieving the values of our class. In .Net we are allowed to override base methods, as long as we use the override Modifier. Our new ToString method looks like this:


#region ToString
/// <summary>
/// here we will override the ToString method in the .Net
/// Framework so when this class is used and called, ToString()
/// will return the path & name of the song
/// </summary>
/// <returns></returns>
public override string ToString()
{
    return _path + "\\" + _name;
}
#endregion




Now that we have our Song Class complete, we will next look at how we can use it, along with the Hashtable Class, to make storing and retrieving data easier and more efficient.


Using The Class

First thing we will be doing is creating an instance of our Song Class, and a Hashtable Object for holding our Song objects. In this tutorial I am referencing a TreeView which I have populated with my music library, but you do not have to use it in this manner, this is just for demonstration purposes. What I did was I created a global variable which is an instance of the Hashtable Class, and an instance of our Song Class:


//Hashtable object to hold our Song objects
Hashtable songs = new Hashtable();
//Create an instance of our Song class
Song song;




I then loop through each checked item in my TreeView Control, and if it has been checked, I create a new Song Object, then add it to my Hashtable, like so:


/// <summary>
/// method for adding all checked items in the TreeView to
/// my Hashtable Object
/// </summary>
private void AddSongs()
{
    //extensions we want to load
    string[] extensions = { ".mp3", ".wma", ".mp4", ".wav" };   
    //now we will loop through all the checked
    //items in our TreeView
    foreach(TreeNode items in tvCurrentLists.Nodes)
    {
        //make sure the node's CheckBox is checked
        if (items.Checked == true)
        {
            //now we will make sure what we're adding is actually a song
            //to do this we will loop through our extensions list
            for (int i = 0; i < extensions.Length; i++)
            {
                //now check the value of the current node
                if (items.FullPath.Contains(extensions[i]))
                {
                    //since it's a song we can now add it to our
                    //Hashtable, only after we create a Song
                    //Object out of it
                    song = new Song("YourPath", items.FullPath);
                    //now add it to our Hashtable
                    songs.Add(song.Name, song);
                }
            }
        }
    }
}




Since we now have our Song Object populated, displaying the values is simply. We will loop through each Song in our Hashtable object, pass in our Key to the indexer, which is the name of the song, then display each song name in a MessageBox, like so:


private void cmdDisplay_Click(object sender, EventArgs e)
{
    //now we will use the Hashtable indexer to display the
    //values of our Hashtable Object
    foreach(Song item in songs)
    {
        //display the value of each song
        MessageBox.Show(songs[item.Name].ToString());
    }
}




Another way we can achieve the same results would be to use the IDictionaryEnumerator Interface to enumerate through each item in our Hashtable object. To do this we will create an instance of the IDictionaryEnumerator Interface, then use the GetEnumerator Method of the Hashtable Class.

To enumerate through the objects in our Hashtable, and to ensure we don't cause any Exceptions by attempting to go past the end of our list, we'll use the MoveNext Method, which equates to true or false depending on the position of the enumerator, like this:


private void cmdDisplay_Click(object sender, EventArgs e)
{
    //variable to hold the list of songs
    string list = string.Empty;
   //create an instance of the IDictionaryEnumerator Interface
    IDictionaryEnumerator enumerator;
    //make sure our Hashtable holds items
    if (songs.Count > 0)
    {
        //let the user know what we're doing
        MessageBox.Show("The following songs are in your list:");
        //now set out IDictionaryEnumerator value
        enumerator = songs.GetEnumerator();
        //now use the MoveNext Method to iterate through our list
        while (enumerator.MoveNext())
        {
            //keep adding song names until we reach the end
            list += enumerator.Value.ToString() + "\r\n";
        }
        //now show the song names
        MessageBox.Show(list);
    }
}




That is how you can effectively use the Hashtable Collection in C#. This tutorial isn't meant to be an all inclusive tutorial, there are many more methods available to you in the Hashtable Class, but I am hoping this will give you enough information to get started using the Hashtable Class, and the IDictionary and IDictionaryEnumerator Interfaces.

As you can see the Hashtable is an efficient way ot storing and retrieving data in your applications, and uses less overhead than other methods because it uses the (Key, Value) pairs to store the data, thus only requiring the Key to retrieve it's value. Using this method doesn't require traditional search methods.

I hope you found this tutorial informative and useful, and thank you for reading :)

Happy Coding!

Is This A Good Question/Topic? 0
  • +

Replies To: Using The C# Hashtable Collection

#2 baavgai  Icon User is online

  • Dreaming Coder
  • member icon

Reputation: 5929
  • View blog
  • Posts: 12,851
  • Joined: 16-October 07

Posted 23 February 2008 - 06:14 AM

First, thank you for all your tutorial work! Also, a Hashtable tutorial is a nice addition.

Unfortunately, from your code and examples, I'm still not sure why I need a Hashtable. Since you're using values in the Key that are already in the Value. You'd be able to do everything present here, in a near identical way, with an ArrayList. Or, even better, a List<>. Indeed, Hashtable is pretty much dropped with the introduction of generics, in favor of proper typed dictionary objects.

Here's your example code:

private void cmdDisplay_Click(object sender, EventArgs e)
{
    //now we will use the Hashtable indexer to display the
    //values of our Hashtable Object
    foreach(Song item in songs)
    {
        //display the value of each song
        MessageBox.Show(songs[item.Name].ToString());
    }
}




However, that key relationship is useless in the example. e.g.

foreach(Song item in songs) {
   //display the value of each song
   MessageBox.Show(item.ToString());
}



The other examples are the same, if you're looping through it, why do you need a key?

A hashtable or dictionary example should show off that I don't need a loop. Also, that my key has meaning beyond my value.

e.g.
Hashtable state = new Hashtable();
state.Add("NE","NEBRASKA");
state.Add("NV","NEVADA");
state.Add("NH","NEW HAMPSHIRE");
state.Add("NJ","NEW JERSEY");
state.Add("NM","NEW MEXICO");
state.Add("NY","NEW YORK");
MessageBox.Show("Welcome to " + state["NJ"]);



I am sorry for such a harsh reply. I enjoy your tutorials and just want them to be as helpful as possible.

This post has been edited by baavgai: 23 February 2008 - 06:16 AM

Was This Post Helpful? 0
  • +
  • -

#3 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4421
  • View blog
  • Posts: 12,286
  • Joined: 18-April 07

Posted 23 February 2008 - 11:11 AM

I just wanted to make a comment about some of what baavgai had said and the intent of this tutorial.

1. The Dictionary object implements a hash table under the hood. It is a specialized hash table.

2. There is tremendous debate between hashtable and dictionary use. The main difference is that hashtable returns null when key not found, dictionary throws an exception. Some of the developers in the industry find this exception throwing overkill and annoying. Some do not. That is the debate.

3. There might be reasons you want to wrap the hashtable class rather than the dictionary object, depending on design. For this reason, it has been kept in.

4. Generics is still a relatively new concept to .NET for the sake of newbies possibly using all sorts of versions, a hashtable tutorial could prove extremely useful.

5. Until the debate is resolved between which is better, hashtable or dictionary, I think we should reserve any judgment on which should be used in comments on this tutorial. As far as newbies are concerned, both are perfectly legit and usable solutions to many of the same problems.

Now as far as the examples of this tutorial, perhaps they could be a bit better than simply looping through it. Psycho is definitely on the write track with the creation of a class and its key. I would modify the tutorial to show attempts to directly access elements rather than just iterating... even though iteration is just a process of accessing, it should not be the only factor on choosing which object to use. Perhaps the data lends itself to being in key table with null being returned... perhaps the collection is a result of numerous repeated records that has been filtered into distinct values (remember hash tables hashes keys to the same location and overwrite existing entries... great for removing duplicate values).

Psycho, I would toss in a small example of showing how a new person can go right into the middle of the list and pluck an entry based on its key only rather than having to loop and find or conduct any other search mechanism. Then it would be a nice complete tutorial in my eyes.

Fantastic work and I highly recommend it to anyone new to the process of using unique key storage, but I also recommend taking a look at dictionary as well. Then decide if it makes more sense to you to have it return null or throw an exception. Your design should tell you which to use.

Great work Psycho. :)

This post has been edited by Martyr2: 23 February 2008 - 11:17 AM

Was This Post Helpful? 0
  • +
  • -

#4 Guest_jazzy*


Reputation:

Posted 05 July 2010 - 05:12 PM

View PostMartyr2, on 23 February 2008 - 10:11 AM, said:

I just wanted to make a comment about some of what baavgai had said and the intent of this tutorial.

1. The Dictionary object implements a hash table under the hood. It is a specialized hash table.

2. There is tremendous debate between hashtable and dictionary use. The main difference is that hashtable returns null when key not found, dictionary throws an exception. Some of the developers in the industry find this exception throwing overkill and annoying. Some do not. That is the debate.

3. There might be reasons you want to wrap the hashtable class rather than the dictionary object, depending on design. For this reason, it has been kept in.

4. Generics is still a relatively new concept to .NET for the sake of newbies possibly using all sorts of versions, a hashtable tutorial could prove extremely useful.

5. Until the debate is resolved between which is better, hashtable or dictionary, I think we should reserve any judgment on which should be used in comments on this tutorial. As far as newbies are concerned, both are perfectly legit and usable solutions to many of the same problems.

Now as far as the examples of this tutorial, perhaps they could be a bit better than simply looping through it. Psycho is definitely on the write track with the creation of a class and its key. I would modify the tutorial to show attempts to directly access elements rather than just iterating... even though iteration is just a process of accessing, it should not be the only factor on choosing which object to use. Perhaps the data lends itself to being in key table with null being returned... perhaps the collection is a result of numerous repeated records that has been filtered into distinct values (remember hash tables hashes keys to the same location and overwrite existing entries... great for removing duplicate values).

Psycho, I would toss in a small example of showing how a new person can go right into the middle of the list and pluck an entry based on its key only rather than having to loop and find or conduct any other search mechanism. Then it would be a nice complete tutorial in my eyes.

Fantastic work and I highly recommend it to anyone new to the process of using unique key storage, but I also recommend taking a look at dictionary as well. Then decide if it makes more sense to you to have it return null or throw an exception. Your design should tell you which to use.

Great work Psycho. :)

Was This Post Helpful? 0

#5 Guest_jazzzyg*


Reputation:

Posted 05 July 2010 - 05:13 PM

Great examples. I have a quick question. Can we implement hashtable in C# in same format as c++ with out own classes holding the data and our own hash algorithm. if someone is aware of that, please let me know.

thanks
Was This Post Helpful? 0

Page 1 of 1