HomeSearch

VB.NET Dictionary Examples

Use Dictionary and add keys and values. Call ContainsKey and TryGetValue to look up elements.
Dictionary. This collection allows fast key lookups. A generic type, it can use any types for its keys and values. Its syntax is at first confusing.
Many functions. Compared to alternatives, a Dictionary is easy to use and effective. It has many functions (like ContainsKey and TryGetValue) that do lookups.
Add example. This subroutine requires 2 arguments. The first is the key of the element to add. And the second is the value that key should have.

Note: Internally, Add() computes the key's hash code value. It then stores the data in the hash bucket.

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

Count: The Count of this dictionary, after 4 Add() calls have run, is 4—a key and value are counted together as 1 entry.

VB.NET program that uses Dictionary Of String Module Module1 Sub Main() ' Create a Dictionary with Add. Dim dictionary As New Dictionary(Of String, Integer) ' Add 4 entries. dictionary.Add("bird", 20) dictionary.Add("frog", 1) dictionary.Add("snake", 10) dictionary.Add("fish", 2) Console.WriteLine("DICTIONARY COUNT: {0}", dictionary.Count) End Sub End Module Output DICTIONARY COUNT: 4
Add, error. If you add keys to the Dictionary and one is already present, you will get an exception. We often must 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.

VB.NET program that uses Add, causes error Module Module1 Sub Main() Dim lookup As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer) lookup.Add("cat", 10) ' This causes an error. lookup.Add("cat", 100) End Sub End Module Output Unhandled Exception: System.ArgumentException: An item with the same key has already been added. at System.ThrowHelper.ThrowArgumentException...
ContainsKey. This 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.

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

VB.NET program that uses ContainsKey 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
TryGetValue. Frequently we test a value through a key in a Dictionary collection. Then we act upon that value. The TryGetValue Function combines the 2 steps. It enables optimizations.

ContainsKey: In the slow version of the code, ContainsKey is called and the Dictionary value is incremented.

TryGetValue: The fast version follows: it only requires 2 lookups because the initial lookup returns the value and we reuse that.

VB.NET program that uses TryGetValue function Module Module1 Sub Main() ' Create a new Dictionary instance. Dim dict As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer) dict.Add("key", 0) ' Slow version: use ContainsKey and then increment at a key. If (dict.ContainsKey("key")) Then dict("key") += 1 End If ' Fast version: use TryGetValue and only do two lookups. Dim value As Integer If (dict.TryGetValue("key", value)) Then dict("key") = value + 1 End If ' Write output. Console.WriteLine(dict("key")) End Sub End Module Output 2
KeyNotFoundException. To see if a key exists in a Dictionary, we should use ContainsKey or TryGetValue. If we just access the key directly, we might get a KeyNotFoundException.

Note: We can use exception handling to detect the KeyNotFoundException, but this will be slower than not causing an exception.

Exception
VB.NET program that shows KeyNotFoundException Module Module1 Sub Main() Dim dict = New Dictionary(Of String, String)() ' We must use ContainsKey or TryGetValue. If dict("car") = "vehicle" Then Return End If End Sub End Module Output Unhandled Exception: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.Collections.Generic.Dictionary`2.get_Item(TKey key)...
Item. 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.

And: You can assign it to a nonexistent key, but you cannot access a nonexistent key without an exception.

Note: Add() may be a better choice than assigning to a key in a Dictionary—it will warn you with an exception if you have a duplicate.

VB.NET program that uses Item assignment Module Module1 Sub Main() Dim dictionary = New Dictionary(Of Integer, Integer)() ' Add data by assigning to a key. dictionary(10) = 20 ' Look up value. Console.WriteLine(dictionary(10)) End Sub End Module Output 20
Loop. 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.

Note: We access the Key and Value properties on each pair. They have the types of the Dictionary keys and values so no casting is required.

VB.NET program that loops over entries 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
Keys. You can get a List of the Dictionary keys. Dictionary has a get accessor property with the identifier Keys. You can pass the Keys 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.

VB.NET program that gets List of keys 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. Dictionary uses typed keys and values. We specify these types when the Dictionary is declared. The compiler disallows incompatible types—here we must use Integers and Strings.
VB.NET program that uses Integer keys 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
ContainsValue. This returns a Boolean that tells whether any value in the Dictionary is equal to the argument. It 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.

VB.NET program that uses ContainsValue 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 use Remove. You must pass one parameter to this method, indicating which key you want to have removed from the Dictionary instance.
VB.NET program that removes keys 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
Copy. It is possible to copy the entire contents of a Dictionary. You can do this by declaring a new Dictionary reference and using the copy constructor.

Tip: In the Dictionary constructor, pass the Dictionary you want to copy as the parameter.

VB.NET program that copies existing Dictionary Module Module1 Sub Main() Dim source = New Dictionary(Of String, Integer)() source.Add("bird", 20) ' Copy the Dictionary. Dim copy = New Dictionary(Of String, Integer)(source) ' Write some details. Console.WriteLine("COPY: {0}, COUNT = {1}", copy("bird"), copy.Count) End Sub End Module Output COPY: 20, COUNT = 1
Field. We use a Dictionary in a class. We store it as Private member variable, and then access it through Public methods on the enclosing class.

Often: A Dictionary field is more useful than a local dictionary variable. This is an effective way to store data and reuse it.

VB.NET program that uses class, Dictionary 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
Count. You can count the number of entries with the Count accessor property. Internally, the Count property subtracts 2 integers. This means it is fast.

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

Property
VB.NET program that uses Count 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
ToDictionary. We can quickly construct a new Dictionary from a collection (array, List) with the ToDictionary extension method. ToDictionary returns a Dictionary.

Functions: We provide 2 functions. These indicate how the key and value are created from the collection's elements.

Here: ToDictionary has 2 lambda arguments. They both receive one argument: the String from the source array.

And: They return a String (for the first, key selector function) and an Integer (for the value selector function).

VB.NET program that uses ToDictionary method Module Module1 Sub Main() ' Create an array of four string literal elements. Dim array() As String = {"dog", "cat", "rat", "mouse"} ' Use ToDictionary. ' ... Use each string as the key. ' ... Use each string length as the value. Dim dict As Dictionary(Of String, Integer) = array.ToDictionary(Function(value As String) Return value End Function, Function(value As String) Return value.Length End Function) ' Display dictionary. For Each pair In dict Console.WriteLine(pair) Next End Sub End Module Output [dog, 3] [cat, 3] [rat, 3] [mouse, 5]
Performance. Dictionary is an optimization for key lookups. It can make a slow program many times faster. But in certain cases a Dictionary reduces performance.

Info: This occurs on small collections. It happens when few lookups are required—a List would be better for storage.

KeyValuePair. This 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
Sort. 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 sort its keys.Sort Dictionary

Keys: With the result of keys, we can convert to a List and then call Sort on the List class.

Notes, reference. 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.

And: The variable and the storage location is stored in the method's stack. So returning, or passing, a Dictionary is fast.

Notes, using Dictionary. In VB.NET, the Dictionary proves to be a common optimization in real programs. It can avoid excessive looping (in a List) to find a matching key.List

And: Knowing the correct usage of a Dictionary proves to be a valuable skill for any VB.NET developer.

A summary. The Dictionary collection is powerful. It is designed for super-fast lookups. It improves the performance of applications. It makes programs simpler by checking for duplicates.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls