September 5th, 2007
To 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.
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 Next
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:
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) Next . . .
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 Next
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) lstEmails.Items.AddRange(EmailKeys)
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.
Entry Filed under: VB.NET Tutorials
Rate This Article: