Hosting - .Net Code

Visual Basic – Generic Collections (Dictionary)

This is basically a List on steroids. Why is that? Because of the way the Dictionary is implemented. Instead of only one argument, you need to specify two. The first one is the Key and the second one is the Value associated to that specific key. Always remember that each key is associated with a specific value. Here is how you declare and initialize a Dictionary in Visual Basic.

Option Explicit On
Option Strict On

Module Program

    Sub Main()
        Dim MyDictionary = New Dictionary(Of Integer, String)

    End Sub

End Module

As you can see, it looks like the List, except we have two types T to declare, the first one is the type of the Key, and the second is the type of the value. For example, if I have students identified by their unique StudentIdentifier. I can use the StudentIdentifier as the key, lets say that it is a 5 digits number, then the key would be an Integer and the value would be the name of the student, which is a String.

Why the Dictionary over a standard List?

Imagine you have a list and a dictionary of 50 000 students. It will take a long time to fetch the whole list of students one by one to find the Student with a specific Name. In a Dictionary, you can find a student almost instantly by using its ID.

Note: Be sure to review your requirements before taking a decision on which collection you will use.

You can think of it as a physical library. What is the first thing you will do when you’re looking for a book. You will conduct a search in the computer to find the book number. Once you have the book number, then you can find the book you’re looking for quickly. That corresponds to the dictionary, as for the list, you would have to go through all the books starting at the first row, it’s nice when the book is in the first ones you will check, but when it’s in the last ones it may take a while to find it.

Behind the Dictionary class is an Hash table. What is an hash table? It’s an array (or multiple) that is organized in a way that when you hash a specific ID (in our case the student number), you can find the value almost instantly. Looks great but the hash table has some down sides, we won’t see them in this tutorial, but if you require more information, you can visit this Website.

Here is a graphic example of what is going on when you retrieve a value using a specific key.

Dictionary

The first step will be to give the key to the dictionary, then the dictionary will hash the key and retrieve the value associated.

Useful Methods

Add(T Key, T2 Value)

Simply add a new key with associated value to the dictionary, similar to adding an item in a List like we’ve seen in tutorial 12.

You can use the add with our Dictionary as follow.

MyDictionary.Add(4, "Alexandre")
MyDictionary.Add(40, "Maxime")
MyDictionary.Add(10, "Daniel")

This code is adding 3 new elements to the Dictionary. Remember that the key is of type Integer and that’s why the first argument is a number. If the key was of type String, then it would be a String, like “AlexStudentID59403” and the value “Alexandre” for example.

TryGetValue

This method is particular as it returns a Boolean value indicating if the element at the specified key as been retrieved successfully and the value as to be a ByRef. What does that means? It means that you have to create the element, it will then be passed to the method and, if the execution went well, the element at the hashed key position will be put into the variable passed. Here is an example to better illustrate.

Dim RetrievedValue As String = String.Empty

If MyDictionary.TryGetValue(4, RetrievedValue) Then
    Console.WriteLine("Student number 4 is {0}", RetrievedValue)
End If

You can see that I created a variable named RetrievedValue with an empty value that will then be passed to the TryGetValue(T Key, T2 Value) method. Once the process is done and the TryGetValue has returned True, then RetrieveValue equals to the value at the key (4) position I asked for. You should test this behavior yourself to make sure you understand perfectly. The ByRef is not something easy at first because it gives a method the possibility to modify a variable outside of its scope.

Remove

The Remove(T Key) method is similar to the List but you only need to pass the Key of the value you wish to remove. If it cannot find the key, the function will return False, if the key/value has been removed, it will return True.

If MyDictionary.Remove(40) Then
    Console.WriteLine("Value at key 40 has been removed!")
Else
    Console.WriteLine("Cannot find value at key 40!")
End If

Contains

You can use Contains(T Key) and Contains(T2 Value) which acts similar to the List as well!

If MyDictionary.ContainsKey(4) Then
   Console.WriteLine("Dictionary contains the key 4!")
End If

Other methods?

The other methods are similar to the List, that is what’s great with Collections.Generic, once you know how to use one collection, learning the others is a lot easier!

Remember, the search process of the Dictionary is faster but it’s not always the best collection to use, you need to think of what you wish you accomplish before you make your selection!

Complete code

Here is the complete commented code for this example!

Option Explicit On
Option Strict On

Module Program

    Sub Main()
        'Declare and initialize a new Dictionary with Key as Integer and Value as String
        Dim MyDictionary = New Dictionary(Of Integer, String)

        'Add values using the Add method
        MyDictionary.Add(4, "Alexandre")
        MyDictionary.Add(40, "Maxime")
        MyDictionary.Add(10, "Daniel")

        Dim RetrievedValue As String = String.Empty

        'Retrieve a value using TryGetValue method
        If MyDictionary.TryGetValue(4, RetrievedValue) Then
            Console.WriteLine("Student number 4 is {0}", RetrievedValue)
        End If

        'Other way to add and retrieve value from Dictionary, I prefer the way above because it's safer
        MyDictionary(5) = "Alex"
        Dim Value As String = MyDictionary(5)
        Console.WriteLine(Value)

        'Remove a value at a specific key in the Dictionary
        If MyDictionary.Remove(40) Then
            Console.WriteLine("Value at key 40 has been removed!")
        Else
            Console.WriteLine("Cannot find value at key 40!")
        End If

        'Verify if the Dictionary contains a key 4
        If MyDictionary.ContainsKey(4) Then
            Console.WriteLine("Dictionary contains the key 4!")
        End If

        Console.ReadKey()
    End Sub

End Module

In the next tutorial we’re going to have a look at the Queue!

Next article Visual Basic - Collections.Generic (Queue)
Previous article Visual Basic - Collections.Generic (List)

Related posts

0 Comments

No Comments Yet!

You can be first to comment this post!

Leave a Comment

Your data will be safe! Your e-mail address will not be published. Also other data will not be shared with third person. Required fields marked as *