List
The VB.NET List
is a resizable array. It stores a variable number of elements in an expandable collection. And it changes its size as needed, on its own.
This type offers many useful methods. We add elements, count elements, and can locate elements with IndexOf
or Find
. With special syntax we initialize lists.
Here we create 2 Lists—each list has 4 elements: 4 Integers of the values 2, 3, 5 and 7. We call Add()
to append to the end of the list. Count
returns the length.
Count
, and get the last element (which is 7) by subtracting 1 from Count
.List
initializer—to create the list.Module Module1 Sub Main() ' Version 1: create list of 4 Integers with Add. Dim list As New List(Of Integer) list.Add(2) list.Add(3) list.Add(5) list.Add(7) Console.WriteLine("LIST 1 COUNT: {0}", list.Count) Console.WriteLine("LIST 1 LAST: {0}", list(list.Count - 1)) ' Version 2: create list with initializer. Dim list2 As New List(Of Integer)({2, 3, 5, 7}) Console.WriteLine("LIST 2 COUNT: {0}", list2.Count) Console.WriteLine("LIST 2 LAST: {0}", list2(list2.Count - 1)) End Sub End ModuleLIST 1 COUNT: 4 LIST 1 LAST: 7 LIST 2 COUNT: 4 LIST 2 LAST: 7
For Each
, ForLooping is an important operation on Lists. We can use For-Each
and For. When an index is not required, the For-Each
loop is a better choice as it is simpler.
List
of Integers. Then, we add 3 integers to the List
contents.List
with a For-Each
loop construct. On each value, "number" refers to the current element.For
-loop. In the upper bound, we subtract 1 from list.Count
. Item()
gets each element by its index.Module Module1 Sub Main() ' Part 1: create List and add 3 Integers. Dim list As New List(Of Integer) list.Add(2) list.Add(3) list.Add(7) ' Part 2: loop through List elements. For Each number As Integer In list Console.WriteLine("FOR EACH: {0}", number) Next ' Part 3: loop through list with a for-to loop. For i As Integer = 0 To list.Count - 1 Console.WriteLine("FOR: {0}", list.Item(i)) Next i End Sub End ModuleFOR EACH: 2 FOR EACH: 3 FOR EACH: 7 FOR: 2 FOR: 3 FOR: 7
Often we have a List
and want to access the first and last elements. The first element is at index 0. The last is at Count
minus one.
Module Program Sub Main() Dim items As New List(Of String)({"X", "T", "Z"}) ' Get first. Dim first As String = items(0) Console.WriteLine("FIRST: {0}", first) ' Get last. Dim last As String = items(items.Count - 1) Console.WriteLine(" LAST: {0}", last) End Sub End ModuleFIRST: X LAST: Z
Count
, ClearThe Count
property returns the total number of elements in the List
. The Clear function removes all the elements so that the next invocation of Count
will return zero.
Count
property and the Clear function on the List
type instance.Module Module1 Sub Main() ' Create a list of booleans. Dim list As New List(Of Boolean) list.Add(True) list.Add(False) list.Add(True) ' Write the count. Console.WriteLine("COUNT: {0}", list.Count) ' Clear the list elements. list.Clear() ' Write the count again. Console.WriteLine("COUNT: {0}", list.Count) End Sub End ModuleCOUNT: 3 COUNT: 0
If
-statementWe often need to scan (or loop) through the elements in the List
and use logical tests on them. We can use a For-Each
loop and then an enclosed If
-statement.
Module Module1 Sub Main() ' Create a list of 3 integers. Dim list As New List(Of Integer)(New Integer() {2, 3, 5}) ' Loop through each number in the list. ' ... Then check it against the integer 3. For Each num As Integer In list If (num = 3) Then Console.WriteLine("Contains 3") End If Next End Sub End ModuleContains 3
Join
The String.Join
function combines an array of strings into a single string
, with a specific delimiter character dividing the parts. A List
, or any IEnumerable
type, can be used with Join
.
Module Module1 Sub Main() ' Create a List of strings, and then use the String.Join method on it. Dim colors As New List(Of String) colors.Add("orange") colors.Add("yellow") colors.Add("mauve") Console.WriteLine(String.Join(",", colors)) End Sub End Moduleorange,yellow,mauve
Dictionary
keysThe List
and Dictionary
collections can be used together. We can acquire a List
of all of the keys from a Dictionary
if needed.
Dictionary
and add 2 keys to it—each key is an Integer, each value is a Boolean
.Keys
by accessing the Keys
property, and then create a new List
with the List
copy constructor.For-Each
loop to enumerate all the Integer keys, writing them to the screen.Module Module1 Sub Main() ' Step 1: create a dictionary, and add 2 pairs. Dim dictionary As New Dictionary(Of Integer, Boolean) dictionary.Add(3, True) dictionary.Add(5, False) ' Step 2: get the list of keys. Dim list As New List(Of Integer)(dictionary.Keys) ' Step 3: loop and display the keys. For Each number As Integer In list Console.WriteLine("KEY: {0}", number) Next End Sub End ModuleKEY: 3 KEY: 5
Insert
The List
is optimized for end-insertion with the Add function. But we can perform a slower insertion in the middle of the List
if needed.
List
.Module Module1 Sub Main() ' Create a list of strings. Dim list As New List(Of String) list.Add("spaniel") list.Add("beagle") ' Insert a string into the list. list.Insert(1, "dalmatian") ' Loop through the entire list. For Each str As String In list Console.WriteLine(str) Next End Sub End Modulespaniel dalmatian beagle
AddRange
, InsertRange
Suppose we want to append or insert an array of Integers into a List
of Integers. We can use the AddRange
or InsertRange
Subs.
String
) must match the target List
's element type.List
into another with AddRange
and InsertRange
—the syntax is the same (just pass a list instead of an array).Module Module1 Sub Main() ' Initial list. Dim list As List(Of Integer) = New List(Of Integer)({1, 2}) ' Add ints on the end. list.AddRange(New Integer() {3, 4}) ' Insert ints at the start. list.InsertRange(0, New Integer() {-2, -1}) ' Display final list. For Each value In list Console.WriteLine("FINAL LIST: {0}", value) Next End Sub End ModuleFINAL LIST: -2 FINAL LIST: -1 FINAL LIST: 1 FINAL LIST: 2 FINAL LIST: 3 FINAL LIST: 4
GetRange
This function returns a range of elements within a List
. We specify (as the first argument) the starting index of the range, and then the number of elements.
List
of several strings. We specify string
literals containing the names of shapes.GetRange
in a For-Each
loop—the loop only calls GetRange
once, and it returns shape names starting at the specified index.Module Module1 Sub Main() ' Step 1: create a List. Dim list As New List(Of String)({"circle", "rectangle", "ellipse", "square", "triangle"}) ' Step 2: call GetRange, and loop through the strings returned by GetRange. For Each value As String In list.GetRange(1, 2) Console.WriteLine("SHAPE: {0}", value) Next End Sub End ModuleSHAPE: rectangle SHAPE: ellipse
Remove
This function removes the first matching element by value. When we pass the value 20 to Remove
, the first matching element is removed from the List
.
Remove()
with a value that is not found in the List
, nothing happens.Module Module1 Sub Main() Dim numbers = New List(Of Integer)({10, 20, 30}) ' Remove this element by value. numbers.Remove(20) For Each number In numbers Console.WriteLine("NOT REMOVED: {0}", number) Next ' This will not change anything. numbers.Remove(3000) End Sub End ModuleNOT REMOVED: 10 NOT REMOVED: 30
IndexOf
This function locates a value within a List
. It searches from the first element and continues through to the last element.
IndexOf
and the value is located in the list. The value 20 occurs at index 1, so 1 is returned.IndexOf
returns -1 if no matching value exists in the List
.Module Module1 Sub Main() Dim sizes As List(Of Integer) = New List(Of Integer) sizes.Add(10) sizes.Add(20) sizes.Add(30) ' Part 1: the value 20 occurs at the index 1. Dim index20 As Integer = sizes.IndexOf(20) Console.WriteLine(index20) ' Part 2: the value 100 does not occur, so IndexOf returns -1. Dim index100 As Integer = sizes.IndexOf(100) If index100 = -1 Then Console.WriteLine("Not found") End If End Sub End Module1 Not found
IEnumerable
The List
(like an array) can be used as an IEnumerable
type—we can pass List
to methods where an IEnumerable
is required. We can then loop over (with For Each
) the collection.
List
and an array in Main
. We pass those of those to the PrintElements
Sub
—it handles all IEnumerable
types.IEnumerable
-receiving functions to share code that must act upon Lists and arrays.Module Module1 Sub Main() ' Create List and pass it as an IEnumerable. Dim list As List(Of Integer) = New List(Of Integer)({10, 20, 30}) PrintElements(list) ' Use array as an IEnumerable. Dim array As Integer() = {100, 200, 300} PrintElements(array) End Sub Sub PrintElements(ByVal elements As IEnumerable(Of Integer)) ' Handle elements in IEnumerable. For Each element In elements Console.WriteLine("Element: {0}", element) Next End Sub End ModuleElement: 10 Element: 20 Element: 30 Element: 100 Element: 200 Element: 300
The VB.NET List
type is a generic, constructed type. It has some performance advantages over other structures, and is useful in many VB.NET programs.