Add Keys: ' Declare New Dictionary With String Keys
Add Keys: ' Declare New Dictionary With String Keys
This
type can use any types for its keys and values. Its syntax is at first confusing. It is overall easy to
use and effective.
Add keys
The Add suroutine re!uires two argu"ents in its para"eter list# the first eing the key of the
ele"ent to add# and the second eing the value that key should have. Internally# the Add
suroutine co"putes the key$s hash code value# and then stores the data in the hash ucket.
And: Because of this step# adding to Dictionary collections is slower than adding to other
collections like %ist.
%ist
Program that uses Dictionary Of String [VB.NET]
Module Module1
Sub Main()
Dim dictionary As New Dictionary(Of String, Integer)
dictionary.Add(Dot, !")
dictionary.Add(Net, 1)
dictionary.Add(#erls, 1")
dictionary.Add($isual, %1)
&nd Sub
&nd Module
The program above will succeed without an exception. But if you add keys to the Dictionary
and one of the keys is already in the Dictionary# you will get an exception. If it is possile the
key already exists# always check with &ontains'ey that the key is not present.
Alternatively: (ou can catch possile exceptions with Try and &atch.
ContainsKey
The &ontains'ey function returns a Boolean value# which "eans you can use it in an If
conditional state"ent. )ne co""on use of &ontains'ey is to prevent exceptions efore calling
Add. Another use is si"ply to see if the key exists in the hash tale# efore 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, ')
dictionary.Add((erl, 1))
' See if this key exists.
If dictionary.*ontains+ey(carrot) ,-en
' Write value of the key.
Dim num As Integer . dictionary.Item(carrot)
*onsole./rite0ine(num)
&nd If
' See if this key also exists (it doesn't).
If dictionary.*ontains+ey((yt-on) ,-en
*onsole./rite0ine(1alse)
&nd If
&nd Sub
&nd Module
Output
'
Using ContainsKey Function. This function in the ase class lirary on the Dictionary type
returns a Boolean value. If the key was found in the Dictionary# it returns True. If the key was
not found# it returns *alse.
Also: (ou can store the result of &ontains'ey in a Di" Boolean# and test that variale with the +
and ,- inary operators.
The Item member is actually a .roperty accessor# which allows you to set or get an ele"ent in
the Dictionary. It is e!uivalent to Add when you assign it.
Tip: (ou can assign it to a nonexistent key# ut you cannot access a nonexistent key with Ite"
without an exception.
oop
(ou can loop over the entries in your Dictionary. It is usually easiest to use the *or Each
iterative state"ent to loop over the 'eyValue.air structures in the Dictionary. In the ody of the
*or Each loop# you can access the 'eyValue.air$s 'ey and Value get accessors.
ote: They have the types of the Dictionary keys and values so no casting is re!uired.
Program that oops o!er 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((lease, 2!)
dictionary.Add(-el(, 13)
dictionary.Add((rogram, !)3)
dictionary.Add(com(uters, %1)
' oo! over entries.
Dim (air As +ey$alue#air(Of String, Integer)
1or &ac- (air In dictionary
4 Dis(lay +ey and $alue.
*onsole./rite0ine(5"6, 516, (air.+ey, (air.$alue)
Ne7t
&nd Sub
&nd Module
Output
(lease, 2!
-el(, 13
(rogram, !)3
com(uters, %1
Key!alue"air. In the ase class lirary# the 'eyValue.air type is i"ple"ented as a /tructure. It
is used as a value and its contents are contains in the variale storage location itself. This can
so"eti"es i"prove perfor"ance.
#et keys
(ou can get a %ist collection of the keys in a Dictionary. Every Dictionary instance has a get
accessor property with the identifier 'eys. (ou can access this collection# and pass it to a %ist
constructor to otain a %ist of the keys. The keys have the sa"e type as that fro" the source
Dictionary.
Program that gets "ist of #eys [VB.NET]
Module Module1
Sub Main()
' Put four keys and values in the Dictionary.
Dim dictionary As New Dictionary(Of String, Integer)
dictionary.Add((lease, 1!)
dictionary.Add(-el(, 11)
dictionary.Add((oor, 1")
dictionary.Add((eo(le, %11)
' Put keys into ist Of String.
Dim list As New 0ist(Of String)(dictionary.+eys)
' oo! over each string.
Dim str As String
1or &ac- str In list
' Print string and also "te#(string)$ which is the value.
*onsole./rite0ine(5"6, 516, str, dictionary.Item(str))
Ne7t
&nd Sub
&nd Module
Output
(lease, 1!
-el(, 11
(oor, 1"
(eo(le, %11
Key types
The Dictionary collection can use any type as its key type and any type for its values. 0owever#
you "ust always specify these types when the Dictionary is declared. This next exa"ple doesn$t
use /tring keys. Instead it uses Integer keys and /tring values.
Program that uses $nteger #eys [VB.NET]
Module Module1
Sub Main()
' Put two "nteger keys into Dictionary Of "nteger.
Dim dictionary As New Dictionary(Of Integer, String)
dictionary.Add(1"", 8ill)
dictionary.Add(!"", Ste9e)
' See if this key exists.
If dictionary.*ontains+ey(!"") ,-en
' Print value at this key.
*onsole./rite0ine(,rue)
&nd If
&nd Sub
&nd Module
Output
,rue
Using type parameters. The part of the progra" after 1New Dictionary1# which contains the 1)f
Integer# /tring1 text# is where the types of the Dictionary instance are declared. The VB.NET
co"piler will disallow any other types eing used as the keys or values.
And: This can result in "uch higher !uality in your code over using 0ashtale.
Contains!alue
2e look at the &ontainsValue .ulic *unction. This function returns a Boolean value that tells
you whether any value in the Dictionary is e!ual to the argu"ent you provide. In the ase class
lirary# this "ethod is i"ple"ented as a *or loop over the entries in the Dictionary. *or this
reason# it provides no perfor"ance advantage over a %ist collection that uses linear searching.
Tip: Accessing keys in your Dictionary is "uch faster.
Program that uses ContainsVaue [VB.NET]
Module Module1
Sub Main()
' %reate new Dictionary with "nteger values.
Dim dictionary As New Dictionary(Of String, Integer)
dictionary.Add((elican, 11)
dictionary.Add(robin, !1)
' See if Dictionary contains the value &' (it does).
If dictionary.*ontains$alue(!1) ,-en
4 #rints true.
*onsole./rite0ine(,rue)
&nd If
&nd Sub
&nd Module
Output
,rue
$emove
0ere we look at an exa"ple of using the 3e"ove function on the Dictionary type. (ou "ust pass
one para"eter to this "ethod# indicating which key you want to have re"oved fro" the
Dictionary instance. If you try to re"ove a key that does not exist in the Dictionary# no
exceptions will e thrown.
Program that remo!es #eys [VB.NET]
Module Module1
Sub Main()
' %reate Dictionary and add two keys.
Dim dictionary As New Dictionary(Of String, Integer)
dictionary.Add(fis-, 2!)
dictionary.Add(microsoft, !2)
' (e#ove two keys.
dictionary.:emo9e(fis-) ' Will re#ove this key.
dictionary.:emo9e(a((le) ' Doesn't change anything.
&nd Sub
&nd Module
Field
In "any progra"s# using Dictionary instances as local variales is not as useful as storing the"
as "e"er variales at the class level. This is ecause they are often used for lookups "ore than
they are used for adding ele"ents.
This e%ample sho&s how you can store a Dictionary instance as .rivate "e"er variale# and
then access it through .ulic "ethods through the enclosing o4ect.
Program that uses cass Dictionary [VB.NET]
Module Module1
''' )su##ary*
''' Stores class+level Dictionary instance.
''' ),su##ary*
*lass &7am(le
#ri9ate ;dictionary
#ublic Sub New()
' Allocate and !o!ulate the field Dictionary.
Me.;dictionary . New Dictionary(Of String, Integer)
Me.;dictionary.Add(ma<e, )))
Me.;dictionary.Add(model, ==)
Me.;dictionary.Add(color, 1!)
&nd Sub
#ublic 1unction >et$alue() As Integer
' (eturn value fro# !rivate Dictionary.
:eturn Me.;dictionary.Item(ma<e)
&nd 1unction
&nd *lass
Sub Main()
' Allocate an instance of the class.
Dim e7am(le As New &7am(le
' Write a value fro# the class.
*onsole./rite0ine(e7am(le.>et$alue())
&nd Sub
&nd Module
Output
))
The Dictionary type is considered a reference type. This "eans it contains a reference or pointer
to the actual data contained in the Dictionary. The actual data is stored in the "anaged heap#
while the variale and the storage location is stored in the "ethod$s stack.
And: *or this reason# using Dictionary as a return type or *unction para"eter is fast.
'%ceptions
5any progra"s that use Dictionary instances extensively will run into the
'eyNot*oundException when looking up values in Dictionary. To prevent these errors# you
"ust always guard your accesses to Dictionary entries using the &ontains'ey "ethod# or the
Try6etValue "ethod. 7sing the Ite"s property will often result in this error.
Dictionary vs. ist
The Dictionary collection in the ase class lirary for the .NET *ra"ework is intended as an
opti"i8ation for key lookups. It can "ake a slow progra" "any ti"es faster# "aking your
chances of getting fired "uch s"aller.
(o&ever) in certain cases the Dictionary will reduce perfor"ance. This will occur on s"all
collections# and also when your progra" has to add keys "uch "ore often than look the" up.
The Dictionary "ust co"pute a hash code each ti"e you add a key.
Count
(ou can count the nu"er of entries in your Dictionary in the VB.NET language y using the
&ount get accessor property. Internally# the &ount property sutracts two integers. This "eans it
is fast and does not slow down even on huge Dictionary instances.
*ote: (ou do not need to specify the parentheses after the &ount property access.
Program that uses Count [VB.NET]
Module Module1
Sub Main()
Dim dictionary As New Dictionary(Of String, Integer)
dictionary.Add(a, ))
dictionary.Add(b, ?)
dictionary.Add(c, 12)
dictionary.Add(d, 1=)
4 >et count.
*onsole./rite0ine(dictionary.*ount)
&nd Sub
&nd Module
Output
=
Copy Dictionary
It is possile to copy the entire contents of the Dictionary in VB.NET# not 4ust the reference
variale. (ou can do this y declaring a new Dictionary reference and using the copy
constructor. In the Dictionary constructor# pass the Dictionary you want to copy as the
para"eter. The entire contents of the Dictionary are copied.
+ort
It is possile to logically sort the keys in a Dictionary type instance. 2hile you cannot directly
"utate the Dictionary$s internal storage to reorder the ele"ents# you can ac!uire the keys fro"
the 'eys property# and then sort the" and loop over that.
ToDictionary
(ou can !uickly construct a new Dictionary instance fro" another collection such as an array or
a %ist using the ToDictionary extension "ethod. &heck out the article on this specific topic for
"ore detail.
+ummary
2e saw "any exa"ples for using the Dictionary type. The Dictionary collection is powerful. It
can i"prove the perfor"ance of applications# and even "ake progra"s si"pler y checking for
duplicates.
+o: 2e looked at adding keys# looping over entries# re"oving keys# looking up values# avoiding
exceptions# and also explored several "ethods on Dictionary