Net-informations.com
SiteMap  | About    

Dictionary in vb.net

How to VB.Net Dictionary

A Dictionary class is a data structure that represents a collection of keys and values pair of data. Each item is a combination of a key and a value. ( key-value pair)

Syntax:

vb.net dictionary sample

Parameters :

TKey - The type of the keys in the dictionary. TValue - The type of the values in the dictionary.

e.g.

Dim dict As New Dictionary(Of String, Integer)()

Adding Values to Dictionary

Add method in Dictionary takes two parameters, one for the key and one for the value.

Syntax:

public void Add(TKey key,TValue value)

e.g.

dictionary.Add("dozen",12)

Key in a Dictionary should not be null, but a value can be, if TValue is a reference type.

Dim dict As New Dictionary(Of String, Integer)() dict.Add("one", 1) dict.Add("two", 2) dict.Add("three", 3) dict.Add("four", 4)

Retrieve Key-Value pair from Dictionary

We can retrieve values from Dictionary using foreach loop

For Each pair As KeyValuePair(Of String, Integer) In dict MsgBox(pair.Key & " - " & pair.Value) Next

Search for a Key

We can search a Key in Dictionary by using the ContainsKey method to test whether a key exists or not. ContainsKey computes the hashcode for its argument and checks the internal structures in the Dictionary.

If dict.ContainsKey("four") = True Then MessageBox.Show(dict("four").ToString()) Else MessageBox.Show("Key does not exist") End If

Iterate over a Dictionary

There are many different ways to iterate over a Dictionary in VB.Net. From the following link you can see in detail .... How to Iterate over a Dictionary

Dictionary Versus HashTable

VB.Net Dictionary and HashTable

Dictionary is a generic type, Hashtable is not. That means you get type safety with Dictionary, because you can't insert any random object into it, and you don't have to cast the values you take out. Since both Dictionary and Hashtable are internally hashtables, so fast access to many-item data according to key, also both need immutable and unique keys. More about.... Dictionary Vs HashTable

Dictionary Versus List

VB.Net Dictionary and List

Both lists and dictionaries are used to store collections of data. The Dictionary is based on a hash table, that means it uses a hash lookup, which is a rather efficient algorithm to look up things, on the other hand, a list you have to go element by element until it finds the result from beginning to the result each time. More about.... Dictionary vs List

Following vb.net program is a full source code of adding and retrieving key values pairs in Dictionary




Dim dict As New Dictionary(Of String, Integer)()
dict.Add("one", 1)
dict.Add("two", 2)
dict.Add("three", 3)
dict.Add("four", 4)

For Each pair As KeyValuePair(Of String, Integer) In dict
    MsgBox(pair.Key & "  -  " & pair.Value)
Next




net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.