C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Step 1: We create Dictionary with String keys, and Integer values. The Dictionary is empty here.
Step 2: We invoke Add to populate the Dictionary. For the arguments, we pass the key we want to add, and the value.
Step 3: 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 Add, Count
Module Module1
Sub Main()
' Step 1: create a Dictionary.
Dim dictionary As New Dictionary(Of String, Integer)
' Step 2: add 4 entries.
dictionary.Add("bird", 20)
dictionary.Add("frog", 1)
dictionary.Add("snake", 10)
dictionary.Add("fish", 2)
' Step 3: display count.
Console.WriteLine("DICTIONARY COUNT: {0}", dictionary.Count)
End Sub
End Module
Output
DICTIONARY COUNT: 4
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...
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
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
Note: We can use exception handling to detect the KeyNotFoundException, but this will be slower than not causing an exception.
ExceptionVB.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)...
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
Step 1: Here we create a Dictionary and add 4 color names to it—blue, yellow, green and red.
Step 2: We access the Key and Value properties on each pair. They have the types of the Dictionary keys and values. No casts are required.
VB.NET program that loops over entries
Module Module1
Sub Main()
' Step 1: create Dictionary with 4 keys.
Dim colors As New Dictionary(Of String, Integer)
colors.Add("blue", 32)
colors.Add("yellow", 16)
colors.Add("green", 256)
colors.Add("red", 100)
' Step 2: use For Each loop over pairs.
For Each pair As KeyValuePair(Of String, Integer) In colors
Console.WriteLine("COLOR: {0}, VALUE: {1}", pair.Key, pair.Value)
Next
End Sub
End Module
Output
COLOR: blue, VALUE: 32
COLOR: yellow, VALUE: 16
COLOR: green, VALUE: 256
COLOR: red, VALUE: 100
Step 1: We create a Dictionary and place 4 String keys (which are all animal names) in it, with Integer values.
Step 2: We use the List constructor on the Keys property. The keys have the same type as that from the source Dictionary.
Step 3: We can loop over the resulting collection. With Item() we can access the value from the Dictionary based on the String key.
For Each, ForVB.NET program that gets List of keys
Module Module1
Sub Main()
' Step 1: add 4 string keys.
Dim animals As New Dictionary(Of String, Integer)
animals.Add("bird", 12)
animals.Add("frog", 11)
animals.Add("cat", 10)
animals.Add("elephant", -11)
' Step 2: get List of String Keys.
Dim list As New List(Of String)(animals.Keys)
' Step 3: loop over Keys and print the Dictionary values.
For Each value As String In list
Console.WriteLine("ANIMAL: {0}, VALUE: {1}", value, animals.Item(value))
Next
End Sub
End Module
Output
please, 12
help, 11
poor, 10
people, -11
Step 1: We create a Dictionary. It has Integer keys and String array values—so each int can point to an entire array.
Step 2: We use ContainsKey. When the key type is Integer, we must pass an Integer to ContainsKey.
IntegerStep 3: We get the String array value with Item, and then call String.Join to concatenate its values.
JoinVB.NET program that uses Integers, String arrays
Module Module1
Sub Main()
' Step 1: use Integer keys, String array values.
Dim dictionary As New Dictionary(Of Integer, String())
dictionary.Add(100, New String() {"cat", "bird"})
dictionary.Add(200, New String() {"dog", "fish"})
' Step 2: see if key exists.
If dictionary.ContainsKey(200) Then
' Step 3: get array value, join elements, and print it.
Dim value() As String = dictionary.Item(200)
Console.WriteLine("RESULT: {0}", String.Join(",", value))
End If
End Sub
End Module
Output
RESULT: dog,fish
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
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
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
Part 1: We begin in the Main Sub. We create a new instance of the Example class.
Part 2: Control enters the New() Sub in the Example class. The Dictionary field is created. We add 3 entries to the Dictionary.
Part 3: We call GetValue() on the Example instance. This returns a value from the Dictionary that was stored with the String key "make."
Tip: A Dictionary field is often more useful than a local 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()
' Part 2: 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()
' Part 1: allocate an instance of the class.
Dim example As New Example
' Part 3: write a value from the class.
Console.WriteLine(example.GetValue())
End Sub
End Module
Output
55
Note: You do not need to specify the parentheses after the Count property access.
PropertyVB.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
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]
Version 1: This version of the code calls ContainsKey on a Dictionary with 1000 String keys.
Version 2: Here we call Contains to find a String key in a List that exists. The element is the 900th one in the List.
Result: The Dictionary is faster. In the List 900 items are looped over, but with hashing in the Dictionary, fewer items are scanned.
VB.NET program that benchmarks Dictionary and List
Module Module1
Sub Main()
' Create Dictionary and List.
Dim lookup As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)
For i As Integer = 0 To 1000
lookup.Add(i.ToString(), 1)
Next
Dim list As List(Of String) = New List(Of String)
For i As Integer = 0 To 1000
list.Add(i.ToString())
Next
Dim m As Integer = 1000
' Version 1: search Dictionary.
Dim s1 As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To m - 1
If Not lookup.ContainsKey("900") Then
Return
End If
Next
s1.Stop()
Dim s2 As Stopwatch = Stopwatch.StartNew
' Version 2: search List.
For i As Integer = 0 To m - 1
If Not list.Contains("900") Then
Return
End If
Next
s2.Stop()
Dim u As Integer = 1000000
Console.WriteLine(((s1.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns"))
Console.WriteLine(((s2.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns"))
End Sub
End Module
Output
35.10 ns Dictionary ContainsKey (1000 keys)
6801.10 ns List Contains (1000 elements)
Keys: With the result of keys, we can convert to a List and then call Sort on the List class.
And: The variable and the storage location is stored in the method's stack. So returning, or passing, a Dictionary is fast.
Info: Knowing the correct usage of a Dictionary proves to be a valuable skill for any VB.NET developer.