Skip to content
Arrays and Collections
step 1/5

Reading — step 1 of 5

Learn

~2 min readSubs, Functions, Arrays

VB.NET has both fixed arrays and modern collections (List, Dictionary).

Arrays

Dim nums(4) As Integer            ' size 5 (0..4) — VB uses INCLUSIVE upper bound
Dim names() As String = {"Ada", "Bob", "Carol"}
Dim auto() = {1, 2, 3, 4, 5}     ' inferred type

nums(0) = 10
nums(1) = 20
Console.WriteLine(nums(0))         ' 10

Beware: Dim nums(4) declares an array with INDICES 0 through 4 — 5 elements. Different from C# where int[4] is 4 elements.

Length:

  • nums.Length — total count
  • nums.GetLength(0) — same
  • UBound(nums) — highest valid index (legacy)

ReDim

Resize an array (loses contents unless you use Preserve):

Dim nums() As Integer = {1, 2, 3}
ReDim Preserve nums(9)            ' grow to 10 elements, keep first 3

Multi-dimensional

Dim matrix(2, 2) As Integer        ' 3x3
matrix(0, 0) = 1
matrix(1, 1) = 5

Dim grid(,) As Integer = {{1, 2, 3}, {4, 5, 6}}

List(Of T)

Dynamic array — usually preferred over arrays:

Imports System.Collections.Generic

Dim list As New List(Of Integer)
list.Add(1)
list.Add(2)
list.Add(3)

list.Count                ' 3
list(0)                   ' 1
list.Remove(2)
list.Sort()

For Each n In list
    Console.WriteLine(n)
Next

Dictionary(Of K, V)

Hash map:

Dim ages As New Dictionary(Of String, Integer)
ages.Add("Ada", 36)
ages("Bob") = 25

ages.ContainsKey("Ada")       ' True
ages("Ada")                    ' 36
ages.Remove("Bob")

For Each kvp In ages
    Console.WriteLine(kvp.Key & ": " & kvp.Value)
Next

LINQ on collections

VB.NET has full LINQ support:

Imports System.Linq

Dim nums = {3, 1, 4, 1, 5, 9, 2, 6}
Dim evens = nums.Where(Function(n) n Mod 2 = 0).ToArray()
Dim doubled = nums.Select(Function(n) n * 2).Sum()
Dim sorted = nums.OrderByDescending(Function(n) n).ToArray()

Query syntax (LINQ-flavored):

Dim result = From n In nums
             Where n > 3
             Select n * 2

This is a major reason to choose VB.NET over older VB6 — the .NET ecosystem.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…