Learn to program in Visual Basic .NET, the right way

Collections - List(Of T)

What are List(Of T)s?

List(Of T), which from this point forward I will refer to as "List" or "Lists", are dynamic collections used to store zero or more values that are the same data type.

List resides in the System.Collections.Generic namespace. Visual Studios will typically reference the namespace by default, but if not (or you're using an online compiler) then you will need to reference the namespace by using the Imports statement.

The T in List(Of T) refers to the data type that the collection will store.

Dynamic Length

Lists fixed the issue that arrays have of not being able to add or remove values from the collection by providing built-in methods.

The example used in the array lesson was the English alphabet. This is because in the alphabet, there are only 26 letters.

Think of a List like a garage. Vehicles can park in the garage or leave at anytime.

Class

List is the first lesson that we have covered thus far that is considered a Class. In later lessons we will go over Classes more in detail, but for now understand that Classes need to be initialized.

The following demonstrates how to initialize a List:

Fiddle: Live Demo

Add Values

There are three built-in methods of adding values to a List:

The Add method will add one value to the end of the collection. The following demonstrates how to add a value to a List using the Add method:

Fiddle: Live Demo

The AddRange method will add an array of values to the end of the collection. The following demonstrates how to add a value to a List using the Add method:

Fiddle: Live Demo

The Insert method will add one value to the collection at a specified index. The following demonstrates how to add a value to a List using the Insert method:

Fiddle: Live Demo

Remove Values

There are several built-in methods of removing values from a List, but for this lesson we will only discuss one:

The RemoveAt method will remove one value from the collection at a specified index. The following demonstrates how to remove a value from a List:

Fiddle: Live Demo

Get Values

Unlike arrays, with Lists to get a value, you get the item by its index from the Item property. The following demonstrates how to remove a value from a List using the Insert method:

Fiddle: Live Demo

Exception

If you try to get a value at either -1 or at an index that is greater than the upper-bounds of the array, then you will receive an IndexOutOfRangeException.

If you are unsure of if the index that you are using will be within the range of the array, then it is best to use a conditional statement to ensure that the index is within range.