Using a Dictionary (Hashtable) - Page 2
       by kirupa  |  13 October 2006

In the previous page you saw some sample code and received a brief overview of what the next few pages hold in store for you. With that, let's begin!

Declaring a Dictionary Object
A Dictionary, similar to a HashTable, takes in two values - a Key and a Value. The key is what you will use to identify the value you are storing. For example, in our above code, the key is the name of the city, and the value is a number representing the density of Starbucks per 10,000 people.

The general form is:

Dictionary<K, V> variable = new Dictionary<K, V>();

The K and V (Key and Value) in the above declaration can also refer to the type (string, int, ArrayList, etc.) of the value you are planning on storing in the K and V fields. Let's take a look at the dictionary declaration from the above code sample:

Dictionary<String, double> coffeeStat = new Dictionary<String, double>();

The coffeeStat variable is declared as a Dictionary object, and its Key/Value pairing takes a String and a double as its object type. Any key used with coffeeStat must be a string, and any value must be a double. You may feel that strongly-typing the values may be restrictive, but it contains many benefits that I will elaborate on at a later time.


Adding Values to our Dictionary
After declaring your values, the next thing you would want to do is add values to your newly created dictionary! To add values, you use the conveniently named Add method:

variable.add(Key, Value);

The key and value you add, like I mentioned earlier, must match the variable type you specified during declaration. In our example, I use strings for the Keys and double numbers for the Value:

coffeeStat.Add("Falls Church, VA", 7.7);
coffeeStat.Add("Katy, TX", 6.8);
coffeeStat.Add("Greenwood Village, CO", 6.3);
coffeeStat.Add("Issaquah, WA", 5.4);
coffeeStat.Add("Palm Beach, FL", 4.8);
// and so on...

Retrieving Values from our Dictionary
With your dictionary populated, to retrieve elements from it, you pass a Key to the dictionary:

variable[Key];

If you are familiar with arrays, then you recognize the similarities in retrieving a value from a dictionary and retrieving a value from the array. The major difference, though, is that you pass an index number to the array, whereas for the dictionary, you pass in data of whatever type you specified your Key to be.

In our example, I print to the console the value returned by the following line of code:

coffeeStat["Palm Beach, FL"];

The value returned by the above code will be 4.8, for we pass in the value "Palm Beach, FL" to the coffeeStat dictionary. If you recall, we bound our "Palm Beach, FL" key to the number 4.8 when adding the values earlier.

Onwards to the next page!

1 | 2 | 3 | 4 | 5




SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.