Visual Basic Dictionary

In visual basic, Dictionary is a generic type of collection and it is useful to store a collection of key/value pairs that are organized based on the key. The dictionary in visual basic will allow storing only the strongly-typed objects i.e. the key/value pairs of the specified data type.

 

In visual basic, while storing the elements in dictionary object, we must need to make sure that the keys are unique because the dictionary object will allow us to store duplicate values but the keys must be unique.

 

The size of dictionary object will vary dynamically so we can add or remove elements from the dictionary object based on our requirements.

 

In visual basic, the dictionary object is same as hashtable object but the only difference is the dictionary object is useful to store a key-value pair of the same data type elements.

Visual Basic Dictionary Declaration

In visual basic, dictionary is a generic type of collection and it is provided by System.Collections.Generic namespace.

 

As discussed, the collection is a class so to define dictionary, we must need to declare an instance of dictionary class before we perform any operations such as add, delete, etc. like as shown below.

 

Dim dct As Dictionary(Of TKey, TValue) = New Dictionary(Of TKey, TValue)()

If you observe the above dictionary declaration, we created a generic dictionary (dct) with an instance of dictionary class using type parameters (TKey, TValue) as placeholders within brackets (Of TKey, TValue).

 

Here, the brackets will indicate that the dictionary is a generic type and type parameter TKey is to represent a type of keys to be accepted by dictionary and TValue is used to represent a type of values to be accepted by dictionary.

 

In visual basic, the generic dictionary (Dictionary(Of T)) is an implementation of IDictionary(Of TKey, TValue) interface so we can also use IDictionary(Of TKey, TValue) interface to create an object of the generic dictionary (Dictionary(Of TKey, TValue)) like as shown below.

 

Dim dct As IDictionary(Of TKey, TValue) = New Dictionary(Of TKey, TValue)()

Visual Basic Dictionary Initialization

Following is the example of initializing a generic dictionary by specifying the required type for key and value.

 

Dim dct As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)()

If you observe the above example, we defined a dictionary (dct) with required key and value types to store. Here, the dictionary object will store a key of string type and value of int type.

Visual Basic Dictionary Properties

Following are the some of commonly used properties of the dictionary object in visual basic programming language.

 

PropertyDescription
Count It is used to get the number of key/value pair elements in dictionary.
Item[TKey] It is used get or set the value associated with the specified key.
Keys It is used get a collection of keys in dictionary.
Values It is used get a collection of values in dictionary.

Visual Basic Dictionary Methods

Following are the some of commonly used methods of the generic dictionary to perform add, search, insert, delete or sort operations in visual basic programming language.

 

MethodDescription
Add It is used to add an elements to dictionary object with specified key and value.
Clear It will remove all the keys and values from the Dictionary<TKey, TValue>.
ContainsKey It is used determine whether the specified key exists in Dictionary<TKey, TValue> or not.
ContainsValue It is used determine whether the specified value exists in Dictionary<TKey, TValue> or not.
Remove It is used to remove an element from Dictionary<TKey, TValue> with specified key.
TryGetValue It is used to get the value associated with the specified key.

Visual Basic Add Elements to Dictionary

As discussed, while adding elements to dictionary object we need to make sure that there will not be any duplicate keys.

 

Following is the example of adding a key/value pair elements to dictionary object in different ways.

 

Module Module1

    Sub Main(ByVal args As String())

        ' Create a new dictionary with int keys and string values.

        Dim dct As Dictionary(Of Integer, String) = New Dictionary(Of Integer, String)()

        ' Add elements to the dictionary object

        ' No duplicate keys allowed but values can be duplicate

        dct.Add(1, "Suresh")

        dct.Add(4, "Rohini")

        dct.Add(2, "Trishi")

        dct.Add(3, Nothing)

        ' Another way to add elements.

        ' If key Not exist, then that key adds a new key/value pair.

        dct(5) = "Trishi"

        ' Add method throws an exception if key already in the dictionary

        Try

            dct.Add(2, "Praveen")

        Catch __unusedArgumentException1__ As ArgumentException

            Console.WriteLine("An element with Key = '2' already exists.")

        End Try

        Console.WriteLine("*********Dictionary1 Elements********")

        ' Accessing elements as KeyValuePair objects

        For Each item As KeyValuePair(Of Integer, String) In dct

            Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value)

        Next

        ' Creating and initializing dictionary

        Dim dct2 As Dictionary(Of String, Integer?) = New Dictionary(Of String, Integer?) From {

                {"msg2", 1},

                {"msg3", 20},

                {"msg4", 100},

                {"msg1", Nothing}

            }

        Console.WriteLine("*********Dictionary2 Elements********")

        ' Accessing elements as KeyValuePair objects

        For Each item As KeyValuePair(Of String, Integer?) In dct2

            Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value)

        Next

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we are able to define a new generic dictionary (dct, dct2) collections. Here, we added only the defined data type keys and values to the newly created dictionaries (dct, dct2) in different ways.

 

As discussed, Add method will throw an exception in case if we try to add a key (2) which is already existing so to handle that exception we used try-catch block.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Add Elements to Dictionary Object Example Result

 

If you observe the above result, we got an exception when we tried to add a key (2) which is already existing and added a key (5) which is not existing in the dictionary.

Visual Basic Access Dictionary Elements

In visual basic, we have different ways to access dictionary elements i.e. either by using index positions or by iterating through the list using ForFor Each loops.

 

Following is the example of accessing dictionary elements in different ways.

 

Module Module1

    Sub Main(ByVal args As String())

        ' Create a new dictionary

        Dim dct As Dictionary(Of Integer, String) = New Dictionary(Of Integer, String)()

        dct.Add(1, "Suresh")

        dct.Add(4, "Rohini")

        dct.Add(2, "Trishi")

        dct.Add(3, "Praveen")

        ' Access value with key (not index)

        Dim val1 As String = dct(2)

        Dim val2 As String = dct(3)

        Dim val3 As String = dct(4)

        Console.WriteLine("******Access Elements with Keys*****")

        Console.WriteLine("Value at Key '2': " & val1)

        Console.WriteLine("Value at Key '3': " & val2)

        Console.WriteLine("Value at Key '4': " & val3)

        Console.WriteLine("*********Access Elements with Foreach Loop********")

        For Each item As KeyValuePair(Of Integer, String) In dct

            Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value)

        Next

        Console.WriteLine("*********Dictionary Keys********")

        For Each item In dct.Keys

            Console.WriteLine("Key = {0}", item)

        Next

        Console.WriteLine("*********Dictionary Values********")

        For Each item In dct.Values

            Console.WriteLine("Value = {0}", item)

        Next

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we are accessing dictionary elements in different ways by using keys and For Each loops based on our requirements.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Access Dictionary Object Elements Example Result

Visual Basic Remove Elements from Dictionary

In visual basic, by using Remove() method we can delete a key/value pair from dictionary object.

 

Following is the example of deleting elements from the dictionary object in visual basic programming language.

 

Module Module1

    Sub Main(ByVal args As String())

        ' Create a new dictionary

        Dim dct As Dictionary(Of Integer, String) = New Dictionary(Of Integer, String)()

        dct.Add(1, "Suresh")

        dct.Add(4, "Rohini")

        dct.Add(2, "Trishi")

        dct.Add(3, "Praveen")

        dct.Add(5, "Sateesh")

        ' Remove element with key (not index)

        dct.Remove(3)

        dct.Remove(5)

        Console.WriteLine("*********Access Dictionary Elements********")

        Console.WriteLine()

        For Each item As KeyValuePair(Of Integer, String) In dct

            Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value)

        Next

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we used Remove() method to delete a particular key of the element from a dictionary.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Remove Elements from Dictionary Object Example Result

Visual Basic Dictionary Check If Item Exists

By using ContainsKey() and ContainsValue() methods, we can check whether the specified key/value elements exists in the dictionary or not. In case, if it exists these methods will return True otherwise False.

 

Following is the example of using ContainsKey() and ContainsValue() methods to check for an item exists in the dictionary or not in visual basic.

 

Module Module1

    Sub Main(ByVal args As String())

        ' Create a new dictionary

        Dim dct As Dictionary(Of Integer, String) = New Dictionary(Of Integer, String)()

        dct.Add(1, "Suresh")

        dct.Add(4, "Rohini")

        dct.Add(2, "Trishi")

        dct.Add(3, "Praveen")

        dct.Add(5, "Sateesh")

        Console.WriteLine("Contains Key 2: {0}", dct.ContainsKey(2))

        Console.WriteLine("Contains Value 'Tutlane': {0}", dct.ContainsValue("Tutlane"))

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we used a ContainsKey() and ContainsValue() methods to check for particular keys and values exist in the dictionary (dct) or not.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Contains Key 2: True

Contains Value 'Tutlane': False

Visual Basic Dictionary Overview

Following are the important points which we need to remember about the dictionary in visual basic.

 

  • Dictionary is useful to store a collection of key/value pairs that are organized by key.
  • Dictionary will allow us to store duplicate values but keys must be unique to identify the values in dictionary.
  • In dictionary, the keys cannot be null but the values can be null.
  • We can access the dictionary elements either by using keys or with For Each loop. In For Each loop we need to use KeyValuePair(Of TKey, TValue) to get a key/value pairs from Dictionary object.

Visual Basic Dictionary vs HashTable

Following are the main differences between hashtable and dictionary in visual basic programming language.

 

  • Hashtable is a non-generic type of collection so it can store an elements of different data types but Dictionary is a generic type of collection so it can store an elements of same data type.
  • Hashtable is available with System.Collections namespace but the dictionary is available with System.Collections.Generic namespace.
  • In For Each loop, we need to use DictionaryEntry property to get the key/value pair from hashtable but we need to use KeyValuePair property to access key/value pair elements from dictionary.
  • When we compared with dictionary object, the hashtable will provide a lower performance because the hashtable elements are of object type so the boxing and unboxing process will occur when we store or retrieve a values from hashtable.
  • In visual basic, the hashtable will throw error if we try to find a key which does not exists but the dictionary object will return null in case the defined key not exists.