Saturday, April 16, 2011

C# Hashtable Use, Lookups and Examples


C# Hashtable Use, Lookups and Examples
Top of Form
Bottom of Form

You want to use the Hashtable collection in the best way, for either an older program written in the C# language or for maintaining a program. The Hashtable provides a fast and simple interface, in many ways simpler than Dictionary. Here we see how you can use the Hashtable collection in the C# programming language, providing a fast lookup collection for hashing keys to values in a constant-time data structure.
Create Hashtable and add entries
First here we see how you can create a new Hashtable with the simplest, parameterless constructor. When it is created, the Hashtable has no values, but we can directly assign values with the indexer, which uses the square brackets [ ]. The example adds three integer keys with one string value each.
Add entries to Hashtable and display them [C#]

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        Hashtable hashtable = new Hashtable();
        hashtable[1] = "One";
    
    hashtable[2] = "Two";
        hashtable[13] = "Thirteen";

        foreach (DictionaryEntry entry in hashtable)
        {
            Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
        }
    }
}

Result

13, Thirteen
2, Two
1, One
Description of the output. The program displays all the DictionaryEntry objects returned from the enumerator in the foreach loop. The WriteLine call contains a format string that displays the key/value pairs with a comma.
Loop over Hashtable key/value pairs
You can loop through the Hashtables by using the DictionaryEntry type in a foreach loop. Alternatively, you can get the Keys collection and copy it into an ArrayList. The DictionaryEntry collection contains two objects, the key and the value. You need to cast these. Please see the section on casting below.
Use Contains, ContainsKey and indexers
Here we see some of the most common and important instance methods on the Hashtable. You will want to call ContainsKey on your Hashtable with the key contents. This methods returns true if the key is found, regardless of the value. Contains works the same way. Finally, we see an example of using the indexer with the [ ] square brackets.
Program that uses Contains method [C#]

using System;
using System.Collections;

class Program
{
    static Hashtable GetHashtable()
    {
        // Create and return new Hashtable.
        Hashtable hashtable = new Hashtable();
        hashtable.Add("Area", 1000);
        hashtable.Add("Perimeter", 55);
        hashtable.Add("Mortgage", 540);
        return hashtable;
    }

    static void Main()
    {
        Hashtable hashtable = GetHashtable();

        // See if the Hashtable contains this key.
        Console.WriteLine(hashtable.ContainsKey("Perimeter"));

        // Test the Contains method. It works the same way.
        Console.WriteLine(hashtable.Contains("Area"));

        // Get value of Area with indexer.
        int value = (int)hashtable["Area"];

        // Write the value of Area.
        Console.WriteLine(value);
    }
}

Output

True
True
1000
Note on the indexer. In C#, an indexer is a property that receives an argument inside square brackets. The Hashtable implements indexers, but it returns plain objects, so you must cast them. See below section for more information on casting. You can find more information on indexers here.
Multiple types in Hashtable and casting
Here we see how you can add multiple types to your Hashtable. This is interesting and is very different from Dictionary generic collections. The example here adds string keys and int keys. Each of the key/value pairs has different types. You can put them all in the same Hashtable.
Program that uses multiple types [C#]

using System;
using System.Collections;

class Program
{
    static Hashtable GetHashtable()
    {
        Hashtable hashtable = new Hashtable();

        hashtable.Add(300, "Carrot");
        hashtable.Add("Area", 1000);
        return hashtable;
    }

    static void Main()
    {
        Hashtable hashtable = GetHashtable();

        string value1 = (string)hashtable[300];
        Console.WriteLine(value1);

        int value2 = (int)hashtable["Area"];
        Console.WriteLine(value2);
    }
}

Output

Carrot
1000
This code might throw exceptions. In C#, casting is a delicate operation and can raise exceptions. If the cast was applied to a different type, the statement could throw an InvalidCastException. You can avoid this by using the 'is' or 'as' statements.
Cast Hashtable value types safely
Here we see ways you can avoid casting problems with your Hashtable. You can use the 'as' operator to attempt to cast an object to a specific reference type. If the cast doesn't succeed, the result will be null. On the other hand, you can use the 'is' operator, which returns true or false based on the result.
Program that casts Hashtable values [C#]

using System;
using System.Collections;
using System.IO;

class Program
{
    static void Main()
    {
        Hashtable hashtable = new Hashtable();
        hashtable.Add(400, "Blazer");

        // This cast will succeed.
        string value = hashtable[400] as string;
        if (value != null)
        {
            Console.WriteLine(value);
        }

        // This cast won't succeed, but won't throw.
        StreamReader reader = hashtable[400] as StreamReader;
        if (reader != null)
        {
            Console.WriteLine("Unexpected");
        }

        // You can get the object and test it.
        object value2 = hashtable[400];
        if (value2 is string)
        {
            Console.Write("is string: ");
            Console.WriteLine(value2);
        }
    }
}

Output

Blazer
is string: Blazer
What's the best way to cast? You can reduce the number of casts and improve performance by using the 'as' operator. This is one performance warning that FxCop, a static analysis tool from Microsoft, will give you.
Keys and Values
Here we note that the Hashtable collection in the C# programming language provides two powerful property accessors that let you access all the keys and values in the collection at once. The properties are called Keys and Values and more information about these properties is available on this website.
Count and Clear methods
Here we mention that the Hashtable collection has a useful Count property accessor that will retrieve and return the number of valid elements in the Hashtable's internal buckets. The Count property is shown in a separate article on this site, along with the Clear method, which is used to show how the Count changes.
Benchmark
Here we look at a benchmark of the Hashtable collection in the System.Collections namespace, versus the Dictionary collection in the System.Collections.Generic namespace. The benchmark first populates an equivalent version of each collection; then it tests one key that is found and one that is not found. It repeats this 20 million times.
Hashtable used in benchmark

Hashtable hashtable = new Hashtable();
for (int i = 0; i < 10000; i++)
{
    hashtable[i.ToString("00000")] = i;
}

Dictionary used in benchmark

var dictionary = new Dictionary<string, int>();
for (int i = 0; i < 10000; i++)
{
    dictionary.Add(i.ToString("00000"), i);
}

Statements benchmarked

hashtable.ContainsKey("09999")
hashtable.ContainsKey("30000")

dictionary.ContainsKey("09999")
dictionary.ContainsKey("30000")

Benchmark of 20 million lookups

Hashtable result:  966 ms
Dictionary result: 673 ms
Interpretation of the benchmark. The Hashtable code is significantly slower than the Dictionary code. I calculate that Hashtable here is 30% slower. This means that for strongly-typed collections, the Dictionary is faster.
Constructors
There are 15 overloaded constructors in the Hashtable class. These provide ways to specify capacities, and let you copy existing collections into the Hashtable. Additionally, you can specify how the hash code is computed and how keys are compared.

No comments:

Post a Comment

Your comment is pending for approval

AngularJS Basics - Part 1

                                                                  AngularJS What is AngularJS ·          Framework by googl...