- 1 What is a VB NET Dictionary?
- 2 Comparing a Dictionary to a list – first
- 3 When to use a VB NET Dictionary?
- 4 How to add values to a VB NET Dictionary?
- 5 Summing everything up
- 6 Downloads
- 7 Related posts
What is a VB NET Dictionary?
A VB NET Dictionary is basically a collection of keys with corresponding values, also called key value pairs. The most common example of a dictionary is something you’ve likely used a lot in your life – especially „back in the days“. I’m talking about a simple phone book, which is storing a matching phone number for each name entry in it.
Before we continue talking about a VB NET Dictionary in detail, we will actually take a step back first. This contrast will help you understand the dictionary better. So let’s first start with a basic thing called „list“, which is essentially – you have guessed it – for listing items.
Comparing a Dictionary to a list – first
So as I mentioned above, we should really compare a dictionaries functionality to a generic list at first, to fully understand the dictionary itself. Let’s now create a list and add some basic entries, we will also add a class for this. I will keep the class pretty simple, just for evaluation purposes.
Create a new class file called „Customer.vb“ and save it.
Public Class Customer Public Property Id As Integer Public Property Name As String Sub New(id As Integer, name As String) Me.Id = id Me.Name = name End Sub End Class
After we have created the class, we will continue by declaring a simple list property inside the forms scope. Next we need to instantiate this declared property, this will happen inside the forms constructor. In the last step, we are then going to add some customer entries/instances, where we will continue working on in a few seconds.
Public Class Form1 Public Property Customers As List(Of Customer) Sub New() InitializeComponent() Customers = New List(Of Customer) End Sub Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Customers.Add(New Customer(1, "Some Ltd.")) Customers.Add(New Customer(2, "Nice Profit Ltd.")) Customers.Add(New Customer(3, "Perfect Devs Ltd.")) End Sub End Class
Finding a specific customer
So one first thing we could want is finding a specific customer inside the generic customer list from above. Usually this would be pretty easy if we would just like „do it“. There are two basic solutions to this, the more oldschool-ish „for each“-approach and the more modern LINQ-approach.
' other code ' ... ' maybe pull this id from something like a TextBox? Dim idToFind = 2 Dim foundCustomer As Customer For Each customer In Customers If customer.Id = idToFind Then foundCustomer = customer Exit For End If Next ' do something with the foundCustomer, if it has been found..
Now, here is the more modern LINQ (which stands for Language Integrated Query) approach, which is basically just one single line. In the background, there’s pretty much the same happening. We’re iterating through each customer and we are using some sort of „is this the customer to be found“-function as a comparison method.
' other code ' ... Dim idToFind = 2 Dim foundCustomer = Customers.SingleOrDefault(Function(x) x.Id = idToFind) ' do something with the foundCustomer, if it has been found..
So what’s the catch?
As you might have already guessed, we need to go through each element in our list to be able to compare the corresponding id to our „idToFind“-variable. Now imagine a list being the size of like 300000 entries. See the results of my tests for those two scenarios below (having just a few entries versus having like 300k entries).
The first test will basically add just like 3 entries to the list and then we would like search for the customer with the id 2. It doesn’t seem like a big deal, but wait – here we are only using a rather unimportant number of data.
Now take a look at the second test, where we will use a lot of data. I’m using 300000 entries and I will be looking for customer id 280000.
Can you spot the drastical performance change? It’s actually insane, in my opinion! In the next section, we will compare this to actually using a dictionary for this same task. For sure, this still is a pretty low time considering us being humans. But imagine these times / performance losses being used in a server app – for sure you want your server to run as smooth as possible. One more thing is, that this time will actually increase even more, by the amount of data inside of our list / lists.
For the next test we are going to look at the „why“, or when you could use a dictionary instead of a list-like thingy. PS: You can also find this test project inside the downloads section of this post.
When to use a VB NET Dictionary?
After the huge performance difference we have seen in the previous tests, we will now take a look at a nice opportunity to actually use the VB NET Dictionary. The dictionary class really shines, when it comes to lookup time – well, it’s the basic thing you do within a dictionary, right? As already mentioned above, it’s just a book of key value pairs.
You can take an existing key, to look up the corresponding value. For sure you can also check, if the dictionary has/contains a specific key. The nice thing is, that this will work at a very nice speed/performance – even on an increasing data basis! Let’s now see the dictionary in action, when it comes to 300000 entries and looking up for example customer id 280000 again.
This is outstanding, isn’t it!? The dictionary just handled the looking up of customer with id 280000 in insanely high speed.
How to add values to a VB NET Dictionary?
After seeing the drastical lookup performance comparison between a simple generic list and the dictionary, it’s time for the next step. Let’s now take a look at actually adding some values to the dictionary. For this, I will switch to a more common thing everyone encounters in his life: A basic phone book.
First we will instantiate a new instance of the dictionary class. This will take two generic arguments, the first one states: „Hey, I want to store some collection with a key of type x“. The second argument states: „Now, I want those keys to actually look up the corresponding value of type y“.
In our example, we will make a string (essentially a name) help us looking up the corresponding phone number. In the end we will have a string key with a matching string value, take a look at the following code. Keep in mind, that I personally prefer the type being infered by the assigned value (when it’s clear).
Dim phoneBook = new Dictionary(Of String, String) ' now add some key value pairs (being names to phone numbers) ' (I just made up those numbers randomly, for sure - don't call them ;)) phoneBook.Add("John Doe", "+491122334567") phoneBook.Add("Christine Doe", "+49188655542") phoneBook.Add("Elon Doe", "+4948862342")
What happens on duplicate keys?
After adding some values you might ask yourself: „But what happens, if I add the same key multiple times?“. Well, we will take a look at this in the next step. I just added a key called „key“ and a value called „value“ to the dictionary two times. This is what will happen:
You will get an „ArgumentException“ residing in the System namespace which basically states: „Hey, you can’t add another entry with the same key called key“.
How to get around duplicate keys in a VB NET Dictionary?
Getting around those added duplicate keys is pretty simple, we just need to use a different method on the dictionary class. The method I’m talking about is named „TryAdd„. It will just try to add the specific value to the dictionary and if this works, you’ll get a „False“ value back, otherwise „True“.
Dim successFullyAdded As Boolean successfullyAdded = phoneBook.TryAdd("John Doe", "+491122334567") ' successfullyAdded will be TRUE here (the first time!) successfullyAdded = phoneBook.TryAdd("John Doe", "+491122334567") ' successfullyAdded will be FALSE here (the second time!)
Alternatively you could also check for duplicate keys beforehand using the „ContainsKey„-method like this.
If phoneBook.ContainsKey("John Doe") Then ' uhoh, the dictionary already contains the name key "John Doe" Else ' feel free to go! End If
Summing everything up
Coming to the end of today’s post, we will finish by summing up the things we saw about a VB NET Dictionary. It basically is – as the name suggests – a collection of keys mapped to their corresponding values. Its biggest advantage is the fast lookup time using a key, which is pretty nice for performance/speed optimized portions of your applications. Keep in mind, that the dictionary itself doesn’t guarantee a specific iteration order everytime, as it keeps no track about that (you can take a look in the documentation for that).