Posted by: Cirilo Meggiolaro | 10/23/2008

Tip of the day #9 – Dictionary or Hashtable? HybridDictionary

Do you want to store data in a key/value pair format but you don’t know how many items will compound your collection?

What if you have large piece of data and sometimes a small amount of items?

You could choose a Hashtable for one scenario or you’d rather a Dictionary object for another.

The answer here is: Use a HybridDictionary object. It works fine in this scenario where the size of your collection is unknown and you want flexibility to handle data.

How to…

/// Namespaces you need
using System.Collections.Specialized;
using System.Collections;

/// Declares and instantiates object
HybridDictionary hybridDic = new HybridDictionary();

/// Add items
hybridDic.Add(“MyKey1”, “MyValue1”);
hybridDic.Add(“MyKey2”, “MyValue2”);
hybridDic.Add(“MyKey3”, “MyValue3”);

/// Loop through items
foreach (DictionaryEntry entry in hybridDic)
Console.WriteLine(“Key: {0} – Value: {1}”, entry.Key, entry.Value);

There are four different contructors’ overloads that allow you to specify an initial size and /or set if case insensitive comparison should be performed.

Add a new item to collection is very straightforward. Just call the Add method passing as parameter the key and the value for the item.

To loop through items you have different ways. The example above describes how to loop using a foreach loop based on dictionary entries but you can use the IDictionaryEnumerator or a for loop instead.

For a complete description about HybridDictionary object, click here!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: