Introduction to the ErrorProvider ComponentLink Round-Up for 9/6/07

Introduction To the Generic Dictionary Class

September 5th, 2007

Use the Dictionary Class to work with data pairsTo continue our review of the generic collection classes, we’ll look at the basics of the Dictionary class and how to use it.

What is a Generic Dictionary?

The generic Dictionary class is a class that maps a set of keys, which can be of any specified type, to a set of values, which also can be of any specified type. The types don’t have be the same for both the key and the value.

Perhaps, if you used VB6, you noticed the Dictionary object. Maybe you used it but many VB6′ers avoided it because it was located in the poor performing Scripting runtime. However, don’t let that ancient history put you off when it comes to the .NET generic Dictionary. This object, which uses internal hash tables, is very fast.

Dictionary Basics

To create a dictionary object, you declare it with the key type first, followed by the value type as seen in these example declarations:

Dim EmailList As New Dictionary(Of String, System.Net.Mail.MailMessage)


Dim Users As New Dictionary(Of Integer, User)


Dim Products As New Dictionary(Of Guid, Product)

To add to the Dictionary, you use the add command where you provide a key and a value, as seen here:

For Each Recipient As String In lstEmails.Items
    If Not EmailList.ContainsKey(Recipient) Then
        EmailList.Add(Recipient, CreateNewMail(Recipient))
    End If

If the specified key already exists in the Dictionary trying to add it again will throw an exception. Therefore, you should use the ContainsKey function to check the collection prior to adding to it, as shown above. Also note that the key can’t be Nothing.

To remove an item, you use the Remove method and provide the key:


Don’t worry, if the item to be removed isn’t in the Dictionary, you won’t get an exception. If it isn’t there a False value is returned.

The items are stored as KeyValuePair objects of the specified types. To retrieve the items in the list individually, you use the Item property where you provide the key and the function returns the value object:

EmailServer.SendAsync(EmailList.Item(txtUserEmail.Text), String.Empty)

You can also enumerate through the list of items. This returns a KeyValuePair object, not the value object, so don’t get confused here (some people do). Here’s an example:

For Each EmailPair As KeyValuePair(Of String, System.Net.Mail.MailMessage) In EmailList
    EmailServer.SendAsync(EmailPair.Value, String.Empty)

You may also update an item in the Dictionary through the Item property:

EmailList.Item(txtUserEmail.Text) = GetHolidayEMail()

Lastly, the Clear method removes all of the keys and values from the Dictionary

Looking at the Contents

As mentioned above, you can use the ContainsKey function to determine if a particular key exists in the Dictionary. There is also the companion function, ContainsValue, that performs the same function for the values.

The TryGetValue method is another way to look up an item in the Dictionary. It combines the functionality of the ContainsKey function and Item property. This method is essentially a helper function that helps you avoid having to catch “Key Not Found” exceptions or doing additional If blocks. Here’s an example of how this method works:

Dim HolidayMailer As System.Net.Mail.MailMessage
For Each Recipient As String In lstEmails.Items
    If EmailList.TryGetValue(Recipient, HolidayMailer) Then
        EmailServer.SendAsync(HolidayMailer, String.Empty)
    End If

In some cases, you might want to extract just the keys or just the values from a dictionary. For example, you may want to get the keys and put them in a ListBox. The Dictionary exposes both as collections in the Keys and Values collections. These are special collection types and they aren’t static copies, but, instead they’re tied back to the Dictionary. Therefore, you should be careful about changing data in them. If you need to simply extract and work with the data separately, you can use the CopyTo function, as seen in this example:

Dim EmailKeys(EmailList.Keys.Count) As String
EmailList.Keys.CopyTo(EmailKeys, 0)

Using Comparison

The Dictionary also allows us to define how we want to determine if a particular key meets equality conditions. For example, let’s assume that you have a Dictionary where you don’t want to have to worry about the case of a key string. You want it to match if the user enters “Smith”, “smith” or even “SMitH”. To do this, we would use a .NET StringComparer as shown here:

Dim HolidayGreetings As New Dictionary(Of String, String)(StringComparer.CurrentCultureIgnoreCase)

Of course, for more complex comparisons, you can code your own comparer but that’s something for another article some other time.

I hope you found this article helpful. Please let me know by leaving a comment or using the rating stars. If you have a question or if you have a subject area you would like for me to cover in more detail, also either leave a comment or use the Contact Me menu button to send me an email.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Entry Filed under: VB.NET Tutorials

Rate This Article:

Not That GoodCould Be BetterOKGoodGreat (3 votes, average: 4 out of 5)
Loading ... Loading ...

2 Comments Add your own

  • 1. Brian Somers  |  June 11th, 2009 at 5:17 pm

    Good article. I have a question. Is it possible to enumerate through and add values to existing keys without specifing the key, just the order the key was added to the dictionary? I have a parsed fix width string that goes through a for loop in a specfic order to get the current field. I have a dictionary that was loaded with keys in the same DB call that loaded the int array for the setfieldwidth property of the parser. So now I want to enumerate through the textfeild parser and add the values to the dictionary.

  • 2. Raja Lakshman  |  December 16th, 2009 at 3:42 am

    Hi Frank

    Great article. I am now thinking maybe I can use the Dictionary class for my Collection classes (instead of Collection(Of T) - the key can be a string and the type can be a GenericType - that way we can load the dictionary with anything and then store the dictionary in the Session - I would like to know your opinion on this - am I on the right track - or is there a better method? Thanks


Leave a Comment


Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed

Visit Me At My New Site, Programming In C#

Most Popular Articles

Highest Rated Articles


Most Recent Articles


 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities