VB.NET Dictionary

Dictionary

Dictionary allows fast key lookups. The VB.NET language provides the Dictionary type. This type can use any types for its keys and values. Its syntax is at first confusing. But Dictionary is overall easy to use and effective.

Add

The Add subroutine requires two arguments. The first is the key of the element to add. And the second is the value that key should have. Internally, Add computes the key's hash code value, and then stores the data in the hash bucket.

And:Because of this step, adding to Dictionary collections is slower than adding to other collections like List.

List
Based on:

.NET 4.5

Program that uses Dictionary Of String: VB.NET

Module Module1
    Sub Main()
	Dim dictionary As New Dictionary(Of String, Integer)
	dictionary.Add("Dot", 20)
	dictionary.Add("Net", 1)
	dictionary.Add("Perls", 10)
	dictionary.Add("Visual", -1)
    End Sub
End Module
Note

The program succeeds without an exception. But if you add keys to the Dictionary and one is already present, you will get an exception. If it is possible the key already exists, always check with ContainsKey that the key is not present.

Alternatively:You can catch possible exceptions with Try and Catch. This often causes a performance loss.

ContainsKey

Key: used to access value

The ContainsKey function returns a Boolean value, which means you can use it in an If conditional statement. One common use of ContainsKey is to prevent exceptions before calling Add.

Also:Another use is simply to see if the key exists in the hash table, before you take further action.

Program that uses ContainsKey: VB.NET

Module Module1
    Sub Main()
	' Declare new Dictionary with String keys.
	Dim dictionary As New Dictionary(Of String, Integer)

	' Add two keys.
	dictionary.Add("carrot", 7)
	dictionary.Add("perl", 15)

	' See if this key exists.
	If dictionary.ContainsKey("carrot") Then
	    ' Write value of the key.
	    Dim num As Integer = dictionary.Item("carrot")
	    Console.WriteLine(num)
	End If

	' See if this key also exists (it doesn't).
	If dictionary.ContainsKey("python") Then
	    Console.WriteLine(False)
	End If
    End Sub
End Module

Output

7
Note

Using ContainsKey Function. This function returns a Boolean value. If the key was found in the Dictionary, it returns True. If the key was not found, it returns False. It is often used in If-statements.

Also:You can store the result of ContainsKey in a Dim Boolean, and test that variable with the = and <> binary operators.

Programming tip

The Item member is a Property accessor. It sets or gets an element in the Dictionary. It is equivalent to Add when you assign it. You can assign it to a nonexistent key, but you cannot access a nonexistent key without an exception.

Loop

Arrow indicates looping

You can loop over the entries in your Dictionary. It is usually easiest to use the For Each iterative statement to loop over the KeyValuePair structures. In the loop, you can access the KeyValuePair's Key and Value get accessors.

For Each

Note:They have the types of the Dictionary keys and values so no casting is required.

Program that loops over entries: VB.NET

Module Module1
    Sub Main()
	' Put four keys into a Dictionary Of String.
	Dim dictionary As New Dictionary(Of String, Integer)
	dictionary.Add("please", 32)
	dictionary.Add("help", 16)
	dictionary.Add("program", 256)
	dictionary.Add("computers", -1)

	' Loop over entries.
	Dim pair As KeyValuePair(Of String, Integer)
	For Each pair In dictionary
	    ' Display Key and Value.
	    Console.WriteLine("{0}, {1}", pair.Key, pair.Value)
	Next
    End Sub
End Module

Output

please, 32
help, 16
program, 256
computers, -1
KeyValuePair: Key and Value properties

KeyValuePair. In the base class library, the KeyValuePair type is implemented as a Structure. It is used as a value. Its contents are contained in the variable storage location itself. This can sometimes improve performance.

KeyValuePair

Keys

List type

You can get a List collection of the Dictionary keys. Dictionary has a get accessor property with the identifier Keys. You can access this collection, and pass it to a List constructor to obtain a List of the keys.

Tip:The keys have the same type as that from the source Dictionary. We can loop over the resulting collection.

Program that gets List of keys: VB.NET

Module Module1
    Sub Main()
	' Put four keys and values in the Dictionary.
	Dim dictionary As New Dictionary(Of String, Integer)
	dictionary.Add("please", 12)
	dictionary.Add("help", 11)
	dictionary.Add("poor", 10)
	dictionary.Add("people", -11)

	' Put keys into List Of String.
	Dim list As New List(Of String)(dictionary.Keys)

	' Loop over each string.
	Dim str As String
	For Each str In list
	    ' Print string and also Item(string), which is the value.
	    Console.WriteLine("{0}, {1}", str, dictionary.Item(str))
	Next
    End Sub
End Module

Output

please, 12
help, 11
poor, 10
people, -11

Types

String type

Dictionary can use any type as its key type and any type for its values. But you must specify these types when the Dictionary is declared. This next example doesn't use String keys. Instead it uses Integer keys and String values.

Program that uses Integer keys: VB.NET

Module Module1
    Sub Main()
	' Put two Integer keys into Dictionary Of Integer.
	Dim dictionary As New Dictionary(Of Integer, String)
	dictionary.Add(100, "Bill")
	dictionary.Add(200, "Steve")

	' See if this key exists.
	If dictionary.ContainsKey(200) Then
	    ' Print value at this key.
	    Console.WriteLine(True)
	End If
    End Sub
End Module

Output

True

Using type parameters. The part after "New Dictionary", which contains the "Of Integer, String" text, is where the types of the Dictionary instance are declared. The compiler disallows any other types being used as the keys or values.

And:This can result in much higher quality in your code over using the Hashtable collection.

ContainsValue

ContainsValue returns a Boolean that tells whether any value in the Dictionary is equal to the argument you provide. In the base class library, this Function is implemented as a For-loop over the entries in the Dictionary.

Tip:ContainsValue has no performance advantage over a List that uses linear searching. Accessing keys in your Dictionary is much faster.

Program that uses ContainsValue: VB.NET

Module Module1
    Sub Main()
	' Create new Dictionary with Integer values.
	Dim dictionary As New Dictionary(Of String, Integer)
	dictionary.Add("pelican", 11)
	dictionary.Add("robin", 21)

	' See if Dictionary contains the value 21 (it does).
	If dictionary.ContainsValue(21) Then
	    ' Prints true.
	    Console.WriteLine(True)
	End If
    End Sub
End Module

Output

True

Remove

Here we look at an example of using the Remove function on the Dictionary type. You must pass one parameter to this method, indicating which key you want to have removed from the Dictionary instance.

Note:If you try to remove a key that does not exist in the Dictionary, no exceptions will be thrown.

Program that removes keys: VB.NET

Module Module1
    Sub Main()
	' Create Dictionary and add two keys.
	Dim dictionary As New Dictionary(Of String, Integer)
	dictionary.Add("fish", 32)
	dictionary.Add("microsoft", 23)

	' Remove two keys.
	dictionary.Remove("fish")  ' Will remove this key.
	dictionary.Remove("apple") ' Doesn't change anything.
    End Sub
End Module

Field

This section provides information

In many programs, using Dictionary instances as local variables is not as useful as storing them as member variables at the class level. This is because they are often used for lookups more than they are used for adding elements.

Here:We store a Dictionary instance as Private member variable, and then access it through Public methods through the enclosing object.

Program that uses class Dictionary: VB.NET

Module Module1
    ''' <summary>
    ''' Stores class-level Dictionary instance.
    ''' </summary>
    Class Example

	Private _dictionary

	Public Sub New()
	    ' Allocate and populate the field Dictionary.
	    Me._dictionary = New Dictionary(Of String, Integer)
	    Me._dictionary.Add("make", 55)
	    Me._dictionary.Add("model", 44)
	    Me._dictionary.Add("color", 12)
	End Sub

	Public Function GetValue() As Integer
	    ' Return value from private Dictionary.
	    Return Me._dictionary.Item("make")
	End Function

    End Class

    Sub Main()
	' Allocate an instance of the class.
	Dim example As New Example

	' Write a value from the class.
	Console.WriteLine(example.GetValue())
    End Sub
End Module

Output

55
Return keyword

Dictionary is a reference type. It contains a reference or pointer to the actual data contained in the Dictionary. The actual data is stored in the managed heap. The variable and the storage location is stored in the method's stack.

And:For this reason, using Dictionary as a return type or Function parameter is fast.

Errors

Warning: exclamation mark

Many programs that use Dictionary instances will run into the KeyNotFoundException when looking up values. To prevent these errors, you must guard your accesses to Dictionary entries using ContainsKey or TryGetValue.

TryGetValue

Performance

The Dictionary collection in the base class library for the .NET Framework is intended as an optimization for key lookups. It can make a slow program many times faster, making your chances of getting fired much smaller.

Performance optimization

However, in certain cases the Dictionary reduces performance. This occurs on small collections. It also happens when your program has to add keys much more often than look them up. Dictionary computes a hash code each time you add a key.

Count

Property

You can count the number of entries with the Count accessor property. Internally, the Count property subtracts two integers. This means it is fast. It does not slow down even on huge Dictionary instances.

Note:You do not need to specify the parentheses after the Count property access.

Property
Program that uses Count: VB.NET

Module Module1
    Sub Main()
	Dim dictionary As New Dictionary(Of String, Integer)
	dictionary.Add("a", 5)
	dictionary.Add("b", 8)
	dictionary.Add("c", 13)
	dictionary.Add("d", 14)

	' Get count.
	Console.WriteLine(dictionary.Count)
    End Sub
End Module

Output

4

Copy

It is possible to copy the entire contents of the Dictionary. You can do this by declaring a new Dictionary reference and using the copy constructor. In the Dictionary constructor, pass the Dictionary you want to copy as the parameter.

Sort

Sorted letters: A to Z

It is possible to logically sort the keys in a Dictionary. You cannot mutate the Dictionary's internal storage to reorder the elements. But you can acquire the keys from the Keys property. You can then sort them and loop over that.

Sort Dictionary

ToDictionary

LINQ: language integrated query

You can quickly construct a new Dictionary instance from another collection such as an array or a List using the ToDictionary extension method. Check out the article on this specific topic for more detail.

ToDictionary

Summary

The VB.NET programming language

We saw many examples for using the Dictionary type. The Dictionary collection is powerful. It improves the performance of applications. It even makes programs simpler by checking for duplicates.

So:We looked at adding keys, looping over entries, removing keys, looking up values and avoiding exceptions.


VB.NET: Collections