How to Create Dictionary In VB.NET

This article explains about dictionary class in VB.NET.
  • 5592

Introduction

A dictionary type represents a collection of keys and values pair of data. The Dictionary class defined in the System.Collections.Generic namespace is a generic class and can store any data types in a form of keys and values. Each key must be unique in the collection. Before you use the Dictionary class in your code, you must import the System.Collections.Generic namespace using the following line.

Imports System.Collections.Generic

Creating a Dictionary

The Dictionary class is a generic class and can store any data types. This class is defined in the code snippet creates a dictionary where both keys and values are string types.

Dim StudentList As New Dictionary(Of String, String)()

The following code snippet adds items to the dictionary.

StudentList.Add("Mahesh", "IT")

StudentList.Add("Suresh", "EC")

StudentList.Add("Raj", "CS")

StudentList.Add("Nitin", "EI")

StudentList.Add("Aman", "ME")

The following code snippet creates a dictionary where the key type is string and value type is short integer.

Dim StudentDetailList As New Dictionary(Of String, Int16)()

The following code snippet adds items to the dictionary.

StudentDetailList.Add("Mahesh", 35)

StudentDetailList.Add("Raj", 25)

StudentDetailList.Add("Suresh", 29)

StudentDetailList.Add("Nitin", 21)

StudentDetailList.Add("Aman", 84)

We can also limit the size of a dictionary. The following code snippet creates a dictionary where the key type is string and value type is float and total number of items it can hold is 3.

Dim PriceList As New Dictionary(Of String, Single)(3)

The following code snippet adds items to the dictionary.

PriceList.Add("Tea", 3.25F)

PriceList.Add("Juice", 2.76F)

PriceList.Add("Milk", 1.15F)

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.