Collections
A collection can be one of many different type or structures in VB.NET. The main structures or types that are used are arrays and list structures. Other structures include hash maps and linked lists. All of these have their advantages, but tend to be increasingly more complex than the previous.
Arrays
An array is a structure that stores multiple sub-variables inside a much larger single entity variable. It is a fixed size sequential collection of elements that are all of the same type. A string is actually an array of characters in most programming languages.
One of the notable things about arrays is that unless declared they start at 0. Arrays can be any size but it must be declared first.
An array with some values of type Integer
where n is the index of the element.
There are two particular ways of declaring an array in VB.NET. The first consists of giving the array values and the second consists of giving the array a fixed length. The first option is shown in the next sample.
Dim array() As String = {"Hello", "World"}
The previous example demonstrates a simple array consisting of 2 elements: "Hello" and "World". Elements within this array can be redeclared with new values. The following sample provides a method to output the array showing the value of each element before a change.
Private Sub OutputArray(ByVal arr() As String) For Each element As String In arr MsgBox(element) Next End Sub Sub Main() Dim array() As String = {"Hello", "World"} OutputArray(array) array(0) = "Hi" OutputArray(array) End Sub
The other option for creating an array is to declare the length of the array and then add elements.
Dim array(1) As String array(0) = "Hello" array(1) = "World"
The same method can be used to read out the second array.
Private Sub OutputArray(ByVal arr() As String) For Each element As String In arr MsgBox(element) Next End Sub Sub Main() Dim array(0)(1) As String array(0) = "Hello" array(0)(1) = "World" OutputArray(array(0)) array(0)(0) = "Hi" OutputArray(array(0)) End Sub
Loops work very much inline with arrays, as shown with the For Each
loop in the examples.
In the same way a character in a string can be accessed
via an index, an array element can be accessed via its index. For a string if the second
character was required it would look something like myString(1)
. The code for an array is very
similar to this code. The following sample demonstrates getting a
specific index from an array, noting that the array begins at the
index 0.
Sub Main() Dim array() As String = {"James", "Jack", "John", "Jamie", "Adam", "Frank"} MsgBox(array(4)) End Sub
The sample should output "Adam".
The previous sample shows how to get the value of one specific element given an index, but this sample leaves room for a looping program that can iterate through the whole array.
Sub Main() Dim array() As String = {"James", "Jack", "John", "Jamie", "Adam", "Frank"} For pos = 0 To 5 MsgBox(array(pos)) Next End Sub
Of course, this is not a very accurate method as it is limited to an array of length 5. The following sample shows how to obtain the length of an array.
Sub Main() Dim array() As String = {"James", "Jack", "John", "Jamie", "Adam", "Frank"} For pos = 0 To array.Length() MsgBox(array(pos)) Next End Sub
System.Array methods
Arrays can do so much more than just iterate through. VB.NET has a wealth of additional
classes that support the framework core. One such class is the System.Array
class.
Reverse
Arrays can be reversed using the Reverse
method of the System.Array
class.
Dim array() As String = {"James", "Jack", "John", "Jamie", "Adam", "Frank"} System.Array.Reverse(array)
Sort
In the same way the Reverse
method is called, the Sort
method
can be used. The Sort
method sorts the array using the VB.NET sort
method.
Dim array() As String = {"James", "Jack", "John", "Jamie", "Adam", "Frank"} System.Array.Sort(array)
IndexOf
The IndexOf
function can be used to find the index of a specific
element within an array.
Dim array() As String = {"James", "Jack", "John", "Jamie", "Adam", "Frank"} MsgBox(System.Array.IndexOf(array, "Jamie"))
Other System.Array methods
There are quite a few other System.Array
methods such as Copy
, BinarySearch
, LastIndexOf
, Find
, Exist
, ForEach
, Resize
and
more that are not being discussed in this article.
Resizing an array
Although resizing an array is not difficult, there are other options to having to resize an array constantly such as using a list structure.
Resizing an array is done using the ReDim
method.
This is demonstrated below:
Dim array() As String = {"James", "Jack", "John", "Jamie", "Adam", "Frank"} ReDim Preserve array(6) array(6) = "Jim" MsgBox(array(6))
Without the Preserve
keyword the array would be empty and all previous elements removed.
Lists
An alternative more flexible way to store multiple sub-variables in the one variable is to use lists. Lists are a generic class of flexible arrays that do not need a length applied. Lists can even be converted to arrays if the need arises.
A list structure is very similar to an array, but instead of
specifying an index to insert a value into, the Add
method is called. All the work for resizing the array is done
behind the scenes.
Add
Dim list As New List(Of String) list.Add("Hello") list.Add("World")
Items can also be inserted at specific indexes as shown in the next sample.
Insert
Dim list As New List(Of String) list.Add("Hello") list.Insert(0, "World")
Remove
As well as both of these methods there exists a method to remove an item. The method relies on an equality test between the specified item and the item in the list. This means that "Hello" ≠ "hello".
Dim list As New List(Of String) list.Add("Hello") list.Add("World") list.Remove("Hello")
Because of the inherent flaws of the Remove
method,
it is often the case that the next method is used instead.
RemoveAt
The RemoveAt
method will remove an element at a
specified index from a list. This can be particularly useful when
coupled with a loop.
Dim list As New List(Of String) list.Add("Hello") list.Add("World") list.Add("My") list.Add("name") list.Add("is") list.Add("Jamie") Dim search As String = "Name" Dim pos As Integer = 0 For Each s As String In list If LCase(s) = LCase(search) Then Exit For End If pos = pos + 1 Next list.RemoveAt(pos)
The Exit For
line is used to leave a For loop at any time.
When removing an element from a list when found, it is essential to
leave the loop before removing the item. Using a pointer to represent the item
may be a good way of getting round this. Another option is to Exit Loop
(where Loop
may be For
, Do
, While
and so on)
so that the pointer for the loop remains the same. The simple reason for not removing
the item when found is that it will modify the collection that the loop is working with
and in turn it will crash the program.
Using the LCase
function to get the lowercase of each string and comparing it is more efficient than performing multiple Remove
methods.
Clear
Lists may also need to be cleared every once in a while. This
is done by performing the Clear
method on the list.
Dim list As New List(Of String) list.Add("Hello") list.Add("World") list.Add("My") list.Add("name") list.Add("is") list.Add("Jamie") list.Clear()
A list can also be redeclared to clear it.
Dim list As New List(Of String) list.Add("Hello") list.Add("World") list.Add("My") list.Add("name") list.Add("is") list.Add("Jamie") list = New List(Of String)
Convert a list to an array
Lists can be converted to arrays because of the similarities between the two types. This is a useful way of avoiding having to resize an array constantly but maintaining it's original array structure.
To convert a list to an array type the ToArray
method is
used.
Dim list As New List(Of String) Dim s() As String s = list.ToArray()
Other list methods
There are a variety of different list methods that are not being
included in this article. Most of the methods are identical to those found in the System.Array
class because of the similar
structure link between lists and arrays.