VB Data Structure
http://vb.net-informations.com/collections/vb.net_collections_tutorials.htm
Visual Basic supports a number of data structures called Collections that holds
data in different ways for flexible operations. The important data structures in
the Collection Classes are ArrayList , HashTable , Stack , Queue etc. From
the following chapters you can see how to manage these data structures in
your visual Basic.net programs.
How to use VB.NET ArrayList ArrayList Example
How to use VB.NET HashTable HashTable Example
How to use VB.NET Stack Stack Example
How to use VB.NET Queue Queue Example
How to use VB.NET Arrays Arrays Example
How to use VB.NET Dyanamic Arrays Dyanamic Arrays Example
How to use VB.NET NameValueCollection NameValueCollection Example
How to use VB.NET List List Example
VB.Net Dictionary example Dictionary example
How to: Declare a Structure Structure
How to VB.NET ArrayList
ArrayList is one of the most flexible data structure from VB.NET Collections. With the Array list
you can add elements to your array dynamically and it accepts null as a valid value and also
allows duplicate elements. Normally Collection class allow you to access an item using either
a numeric index or a String key, but ArrayList allows only a numeric index. ArrayList is flexible
because we can add items without any size information.
vb-arraylist
Important functions from ArrayList Object
Add : Add Items in an ArrayList
Insert : Insert Items to a specified position in an ArrayList
Remove : Remove an Item from ArrayList
RemoveAt: remove an item from a specified position
Sort : Sort Items in an ArrayList
How to add Items in an ArrayList ?
Syntax : ArrayList.add(Item)
Item : The Item to be add the ArrayList
Dim ItemList As New ArrayList()
ItemList.Add("Item4")
How to Insert Items in an ArrayList ?
Syntax : ArrayList.insert(index,item)
index : The position of the item in an ArrayList
Item : The Item to be add the ArrayList
ItemList.Insert(3, "item6")
How to remove an item from arrayList ?
Syntax : ArrayList.Remove(item)
Item : The Item to be add the ArrayList
ItemList.Remove("item2")
How to remove an item in a specified position from an ArrayList ?
Syntax : ArrayList.RemoveAt(index)
index : the position of an item to remove from an ArrayList
ItemList.RemoveAt(2)
How to sort ArrayList ?
Syntax : ArrayListSort()
From the following Visual Basic source code you can see some important operations from an
ArrayList Object
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim ItemList As New ArrayList()
ItemList.Add("Item4")
ItemList.Add("Item5")
ItemList.Add("Item2")
ItemList.Add("Item1")
ItemList.Add("Item3")
MsgBox("Shows Added Items")
For i = 0 To ItemList.Count - 1
MsgBox(ItemList.Item(i))
Next
'insert an item
ItemList.Insert(3, "Item6")
'sort itemms in an arraylist
ItemList.Sort()
'remove an item
ItemList.Remove("Item1")
'remove item from a specified index
ItemList.RemoveAt(3)
MsgBox("Shows final Items the ArrayList")
For i = 0 To ItemList.Count - 1
MsgBox(ItemList.Item(i))
Next
End Sub
End Class
When you execute this program , it add five items in the arraylist and displays using a for loop
statement. Then again one more item inserted in the third position , and then sort all items.
Next it remove the item1 and also remove the item from the third position . Finally it shows
the existing items.
How to VB.Net HashTable
HashTable stores a Key Value pair type collection of data . We can retrive items from
hashTable to provide the key . Both key and value are Objects.
The common functions using in Hashtable are :
Add : To add a pair of value in HashTable
Syntax : HashTable.Add(Key,Value)
Key : The Key value
Value : The value of corrosponding key
ContainsKey : Check if a specified key exist or not
Synatx : HashTable.ContainsKey(key)
Key : The Key value for search in HahTable
ContainsValue : Check the specified Value exist in HashTable
Synatx : HashTable.ContainsValue(Value)
Value : Search the specified Value in HashTable
Remove : Remove the specified Key and corrosponding Value
Syntax : HashTable.Remove(Key)
Key : The argument key of deleting pairs
The following source code shows all important operations in a HashTable
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim weeks As New Hashtable
Dim day As DictionaryEntry
weeks.Add("1", "Sun")
weeks.Add("2", "Mon")
weeks.Add("3", "Tue")
weeks.Add("4", "Wed")
weeks.Add("5", "Thu")
weeks.Add("6", "Fri")
weeks.Add("7", "Sat")
'Display a single Item
MsgBox(weeks.Item("5"))
'Search an Item
If weeks.ContainsValue("Tue") Then
MsgBox("Find")
Else
MsgBox("Not find")
End If
'remove an Item
weeks.Remove("3")
'Display all key value pairs
For Each day In weeks
MsgBox(day.Key " -- " day.Value)
Next
End Sub
End Class
When you execute this program it add seven weekdays in the hashtable and display the item
5. Then it check the item "Tue" is existing or not . Next it remove the third item from
HashTable. Finaly it displays all item exist in the HashTable.
How to Create VB.Net Stack
Stack is one of another easy to use VB.NET Collections . Stack follows the push-pop
operations, that is we can Push Items into Stack and Pop it later also it follows the Last In First
Out (LIFO) system. That is we can push the items into a stack and get it in reverse order. Stack
returns the last item first.
Commonly used methods :
Push : Add (Push) an item in the stack datastructure
Syntax : Stack.Push(Object)
Object : The item to be inserted.
Pop : Pop return the item last Item to insert in stack
Syntax : Stack.Pop()
Return : The last object in the Stack
Contains : Check the object contains in the stack
Syntax : Stack.Contains(Object)
Object : The specified Object to be search
The following VB.NET Source code shows some of commonly used functions :
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim stackTable As New Stack
stackTable.Push("Sun")
stackTable.Push("Mon")
stackTable.Push("Tue")
stackTable.Push("Wed")
stackTable.Push("Thu")
stackTable.Push("Fri")
stackTable.Push("Sat")
If stackTable.Contains("Wed") Then
MsgBox(stackTable.Pop())
Else
MsgBox("not exist")
End If
End Sub
End Class
When you execute this program add seven items in the stack . Then its checks the item "Wed"
exist in the Stack. If the item exist in the Stack , it Pop the last item from Stack , else it shows
the msg "Not Exist"
How to VB.Net Queue
The Queue is another adtastructure from VB.NET Collections . Queue works like First In First
Out method and the item added first in the Queue is first get out from Queue. We can
Enqueue (add) items in Queue and we can Dequeue (remove from Queue ) or we can Peek
(that is get the reference of first item added in Queue ) the item from Queue.
The commonly using functions are follows :
Enqueue : Add an Item in Queue
Syntax : Stack.Enqueue(Object)
Object : The item to add in Queue
Dequeue : Remove the oldest item from Queue (we don't get the item later)
Syntax : Stack.Dequeue()
Returns : Remove the oldest item and return.
Peek : Get the reference of the oldest item (it is not removed permenantly)
Syntax : Stack.Peek()
returns : Get the reference of the oldest item in the Queue
The following VB.NET Source code shows some of commonly used functions :
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles Button1.Click
Dim queueList As New Queue
queueList.Enqueue("Sun")
queueList.Enqueue("Mon")
queueList.Enqueue("Tue")
queueList.Enqueue("Wed")
queueList.Enqueue("Thu")
queueList.Enqueue("fri")
queueList.Enqueue("Sat")
MsgBox(queueList.Dequeue())
MsgBox(queueList.Peek())
If queueList.Contains("Sun") Then
MsgBox("Contains Sun ")
Else
MsgBox("Not Contains Sun ")
End If
End Sub
End Class
When you execute the program it add seven items in the Queue. Then it Dequeue (remove)
the oldest item from queue. Next it Peek() the oldest item from Queue (shows only , not
remove ). Next it check the Item "Sun" contains in the Queue.
How to VB.Net Arrays
Arrays are using for store similar data types grouping as a single unit. It is a fixed collection of
same data type that are stored contiguously and that are accessible by an index We specify
their length and we can initialize arrays with data. We can access Array elements by its
numeric index.
vb.net array
Integer Array
Declaring and Initializing an Integer Array
Dim array As Integer() = New Integer(3) {}
array(0) = 10
array(1) = 20
array(2) = 30
array(3) = 40
In the above code we declare an Integer Array of four elements and assign the value to array
index . That means we assign values to array index 0-3.
We can retrieve these values from array by using a for loop.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim array As Integer() = New Integer(3) {}
array(0) = 10
array(1) = 20
array(2) = 30
array(3) = 40
For i As Integer = 0 To array.Length - 1
MessageBox.Show(array(i))
Next
End Sub
End Class
We can declare and initialize an array in one statement.
Dim array As Integer() = New Integer() {10, 20, 30, 40}
Note that in the above code we did not specify the length of the array so the compiler will do
it for us.
How to find the length of an Array ?
array.Length
We can use array.Length to find the length of an Array.
String Array
Declaring and Initializing a String Array
Dim week(6) As String
The above Vb.Net statements means that , an Array named as week declared as a String type
and it can have the capability of seven String type values.
week(0) = "Sunday"
week(1) = "Monday"
In the above statement , we initialize the values to the String Array. week(0) = "Sunday"
means , we initialize the first value of Array as "Sunday" ,
Dim weekName as String = week(1)
We can access the Arrays elements by providing its numerical index, the above statement we
access the second value from the week Array.
In the following program , we declare an Array "week" capability of seven String values and
assigns the seven values as days in a week . Next step is to retrieve the elements of the Array
using a For loop. For finding the end of an Array we used the Length function of Array Object.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim week(6) As String
week(0) = "Sunday"
week(1) = "Monday"
week(2) = "Tuesday"
week(3) = "Wednesday"
week(4) = "Thursday"
week(5) = "Friday"
week(6) = "Saturday"
For i = 0 To week.Length - 1
MsgBox(week(i))
Next
End Sub
End Class
How to resize an array ?
An array can be resized with Array.Resize < T > Method , that means We make an array
bigger or smaller. Array.Resize < T > Method Changes the number of elements of a
one-dimensional array to the specified new size.
Array.Resize < T > - T is the type of the elements of the array.
This method should be used with only one dimensional Array. This method allocates a new
array with the specified size, copies elements from the old array to the new one, and then
replaces the old array with the new one.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim sArray As Char() = New Char(4) {}
sArray(0) = "A"
sArray(1) = "B"
sArray(2) = "C"
sArray(3) = "D"
sArray(4) = "E"
For i As Integer = 0 To sArray.Length - 1
MessageBox.Show(sArray(i).ToString())
Next
Array.Resize(sArray, 3)
For i As Integer = 0 To sArray.Length - 1
MessageBox.Show(sArray(i).ToString())
Next
End Sub
End Class
Array.Resize(sArray, 3)
In the above code we resize the array to 3 elements.
How to Use For Each loop with Arrays ?
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim array As Integer() = {10, 30, 50}
'array declaration
For Each element As Integer In array
MsgBox(element)
Next
End Sub
End Class
Array Sort
sort array in VB.Net ascending descending Reverse array
You can sort the arrays in ascending order as well as descending . We can use Array.Sort
method for sorts the elements in a one-dimensional array. Also we can use Array.Reverse
method for reverses the sequence of the elements in the entire one-dimensional Array. Click
the following link to see .... How to sort VB.Net Arrays
The following source code shows how to sort an integer Array in ascending order.
Dim arr As Integer() = New Integer() {3, 1, 4, 5, 2}
Array.Sort(arr)
For Each str As Integer In arr
MsgBox(str)
Next
The following code shows how to sort an Integer array in reverse order.
Dim arr As Integer() = New Integer() {3, 1, 4, 5, 2}
Array.Sort(arr)
Array.Reverse(arr)
For Each str As Integer In arr
MsgBox(str)
Next
How to Create an Array with different data types
You can create an array with elements of different data types when declare the array as
Object. Since System.Object is the base class of all other types, an item in an array of Objects
can have a reference to any other type of object. More about.... Multiple data types in an
Array - VB.Net
System.Array.CopyTo and System.Array.Clone()
The System.Array.CopyTo method copies the elements into another pre-existing array
starting from a given index. The System.Array.Clone() method returns a new array object,
which means that the destination array need not exist yet since a new one is created from
scratch with containing all the elements in the original array. More about the difference
between .... System.Array.CopyTo and System.Array.Clone()
How to check if a value exists in an array ?
The following program shows how to find a specified value from an Array.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim stringToCheck As String = "GHI"
Dim stringArray As String() = {"ABC", "DEF", "GHI", "JKL"}
For Each x As String In stringArray
If x.Equals(stringToCheck) Then
MessageBox.Show("Find the string ..." + x)
End If
Next
End Sub
End Class
When you execute this program you will get the Days in a Week .
How to VB.Net Dyanamic Array
Dynamic Arrays can resize the capability of the Array at runtime .when you are in a situation
that you do not know exactly the number of elements to store in array while you making the
program. In that situations we are using Dynamic Array .
Initial declaration
Dim scores() As Integer
Resizing
ReDim scores(1)
If you want to keep the existing items in the Array , you can use the keyword Preserve .
ReDim Preserve scores(2)
In this case the Array dynamically allocate one more String value and keep the existing values.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim scores() As Integer
ReDim scores(1)
scores(0) = 100
scores(1) = 200
For i = 0 To scores.Length - 1
MsgBox(scores(i))
Next
ReDim Preserve scores(2)
scores(2) = 300
For i = 0 To scores.Length - 1
MsgBox(scores(i))
Next
End Sub
End Class
When you execute this source code , the first loop shows first two values stored in the Array.
Next loop shows the whole value stored in the Array.
How to VB.Net NameValueCollection
NameValueCollection is used to store data like Name, Value format. It is very similar to
Vb.Net HashTable, HashTable also stores data in Key , value format . NameValueCollection
can hold more than one value for a corresponding Key.
Adding new pairs
Add(ByVal name As String, ByVal value As String)
Add("High","80")
Get the value of corresponding Key
GetValues(ByVal name As String) As String()
String values() = GetValues("High")
Imports System.Collections.Specialized
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim markStatus As New NameValueCollection
Dim key As String
Dim values() As String
markStatus.Add("Very High", "80")
markStatus.Add("High", "60")
markStatus.Add("medium", "50")
markStatus.Add("Pass", "40")
For Each key In markStatus.Keys
values = markStatus.GetValues(key)
For Each value As String In values
MsgBox(key & " - " & value)
Next value
Next key
End Sub
End Class
When you execute this source code , you will get each Key/Value sets.
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
How to use VB.NET List
VB.NET List examples
Generic lists were introduced with .Net 2.0 and are the way to go. List is a generic
implementation of ArrayList. List can store only one type of objects, that type supplied as its
generic parameter. List class is a collection and defined in the System.Collections.Generic
namespace and it provides the methods and properties like other Collection classes such as
add, insert, remove, search etc.
To use List(Of T), however, you have to understand how to implement the many methods that
the .NET Framework provides
List(Of T)
The parameter T is the type of elements in the list.
How to add items in List ?
Add integer values in the List
Dim iList As New List(Of Integer)()
iList.Add(2)
iList.Add(3)
iList.Add(5)
iList.Add(7)
Add string values in the List
Dim numbers As New List(Of String)()
numbers.Add("One")
numbers.Add("Two")
numbers.Add("Three")
How to count number of items exists in a List ?
List.Count property gives you the number of items exists in List
numbers.Count
How to retrieve items from List ?
You can retrieve items from List collection by using for loops.
for each loop
For Each number As String In numbers
MessageBox.Show(number)
Next
for loop
For i As Integer = 0 To numbers.Count - 1
MessageBox.Show(numbers(i))
Next
How to insert an item in the List ?
You can use insert(index,item) method to insert an in the specified index.
numbers.Insert(1, "zero")
In the above code the number "zero" is inserted in the index position 1.
How to remove an item from List collection?
List.Remove() can use to remove item from List.
numbers.Remove("zero");
How to check if an item exist in the List ?
You can use List.Contains() method to check an item exists in the List
if (numbers.Contains("Two"))
MessageBox.Show("Number Two exist in the list");
How to copy an Array to a List ?
Dim strArr As String() = New String(2) {}
strArr(0) = "Red"
strArr(1) = "Blue"
strArr(2) = "Green"
//here to copy array to List
Dim arrlist As New List(Of String)(strArr)
Finally clear method remove all the items from List collection.
arrlist.Clear()
Difference between list and dictionary in VB.Net
In VB.Net applications both lists and dictionaries are used to store collections of data. List
(ICollection ) is simply a set of items and Dictionary(IDictionary) is a set of key-value pairs. The
essential difference therefore is in how the containers are indexed data in your VB.Net
application. If you want to know more details.....What is the difference between list and
dictionary in VB.Net?
The following VB.Net program shows the implementation of the above functionalities in List
collection.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim numbers As New List(Of String)()
'add items in a List collection
numbers.Add("One")
numbers.Add("Two")
numbers.Add("Three")
'insert an item in the list
numbers.Insert(1, "Zero")
'retrieve items using foreach loop
For Each number As String In numbers
MessageBox.Show(number)
Next
'remove an item from list
numbers.Remove("Zero")
'retrieve items using for loop
For i As Integer = 0 To numbers.Count - 1
MessageBox.Show(numbers(i))
Next
If numbers.Contains("Two") Then
MessageBox.Show("Number two exist in the list")
Else
MessageBox.Show("Not exist")
End If
'copy array to list
Dim strArr As String() = New String(2) {}
strArr(0) = "Red"
strArr(1) = "Blue"
strArr(2) = "Green"
Dim arrlist As New List(Of String)(strArr)
For Each str As String In strArr
MessageBox.Show(str)
Next
'call clear method
arrlist.Clear()
MessageBox.Show(arrlist.Count.ToString())
End Sub
End Class
How to: Declare a Structure
https://msdn.microsoft.com/en-us/library/4ft0z102.aspx
1. Create the beginning and ending statements for the structure.
You can specify the access level of a structure using the Public, Protected, Friend, or Private
keyword, or you can let it default to Public.
Private Structure employee
End Structure
2. Add elements to the body of the structure.
A structure must have at least one element. You must declare every element and specify an
access level for it. If you use the Dim Statement without any keywords, the accessibility
defaults to Public.
Example:
Private Structure employee
Public givenName As String
Public familyName As String
Public phoneExtension As Long
Private salary As Decimal
Public Sub giveRaise(raise As Double)
salary *= raise
End Sub
Public Event salaryReviewTime()
End Structure
The salary field in the preceding example is Private, which means it is inaccessible outside the
structure, even from the containing class. However, the giveRaise procedure is Public, so it
can be called from outside the structure. Similarly, you can raise the salaryReviewTime event
from outside the structure.