Dictionaries in C#: The ListDictionary

Hashtables (see my posts from the last two days ago) are a great, general use type of dictionary, but they have the one drawback of requiring some extra overhead to implement. For very small collections, say 10 items or less, the overhead can have an impact on performance. To solve this, Microsoft has created an alternate form of hashtable called a ListDictionary.

Behind the scenes, ListDictionaries are implemented as simple arrays. For small collections then their performance is very fast. They have the same interface as a hashtable, so it’s very easy to swap from one to another, aside of course from the issue of having to recompile your project.

Before starting, in addition to the using System.Collections reference, you will also need to include a using System.Collections.Specialized reference to the top of your code.

Next, all you have to do is create a variable of type ListDictionary. After that, using it is identical to using a HashTable.

      ListDictionary genders = new ListDictionary();

 

      genders.Add(“M”, “Male”);

      genders.Add(“F”, “Female”);

 

Frequently when dealing with collections the size of the collection is quite small. Lists of values for drop down boxes, which hold data for things like employee type, gender, ethnicity, and perhaps ranges of ages are all times when you will have a short list. For those times, when you are certain the list is small, use a ListDictionary to increase the performance of your application.

Advertisements

One Response to “Dictionaries in C#: The ListDictionary”

  1. Joseph N. Musser II Says:

    Actually, ListDictionaries are implemented as linked lists rather than simple arrays.


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: