Visual Basic Lists

Lists, like arrays, can contain multiple values of the same type, however they are a lot more flexible than arrays, due to the ease of adding and removing values. Unlike with arrays, the number of values in a list does not have to be specified when it is defined.

The example below creates a list of strings called ‘fname’, adds four names using the ‘Add’ method of the list, then, using a ‘For Each’ loop, displays the names in the console.

Dim fname As New List(Of String)()

fname.Add("Bob")
fname.Add("George")
fname.Add("Fred")
fname.Add("Alan")

For Each name As String In fname
    Console.WriteLine(name)
Next

The output from this will be as follows.

Bob
George
Fred
Alan

The declaration and initialisation of the list can be done more efficiently by combining the two, whilst still allowing the ‘For Each’ loop to process the list in the same way.

Dim fname As New List(Of String)(New String() {
   "Bob",
   "George",
   "Fred",
   "Alan"
})

Note that, like with an array, an ordinary ‘For’ loop could be used, but a ‘For Each’ loop is simpler.

In order to add another name to the list it is just a case of repeating how “George”, “Bob”, “Fred” and “Alan” were added in the first example above.

fname.Add("Andrew")

Items from a list can also be removed in a similar fashion.

fname.Remove("Andrew")

An alternative method of removing an item from a list is to specify the items index value. As with arrays, a list is zero based, so the first item in the list has an index value of zero not one. The following example would remove “George” at index position one in the list.

fname.RemoveAt(1)

If it is necessary to access just one value in a list, for example, to display it in the console, then the index value can again be used. Here, the first name in the list is output to the console.

Console.WriteLine(fname(0))

It is also possible to sort items in a list using the ‘Sort’ method of the list.

fname.Sort()

If the items required in a list already exist in an array, it is possible to add the contents of the array in to a list in one line of code, using the ‘AddRange’ method of a list.

Dim fnameArray = New String() {"Bob", "George", "Fred", "Alan"}
Dim fname As New List(Of String)()

fname.AddRange(fnameArray)