Arrays, Collections and Data Structures

8.1 Arrays

Dim a(4) As Integer                     ' 5 elements (upper bound 4)
Dim b() As String = {"x", "y"}
Dim grid(2, 2) As Integer               ' rectangular
Dim jag()() As Integer = {New Integer() {1, 2}, New Integer() {3}}
ReDim Preserve a(9)
Array.Sort(b) : Array.Reverse(b) : Array.IndexOf(b, "y")
Dim copy = DirectCast(a.Clone(), Integer())
Dim filled = Enumerable.Repeat(0, 10).ToArray()

8.2 Choosing a Collection

Ordered, index access O(1) amortized at the end Dictionary(Of TKey, TValue)

SortedDictionary (tree) / SortedList (array) O(log n) / O(n) HashSet(Of T) / SortedSet(Of T) O(1) / O(log n) Queue(Of T) / Stack(Of T) PriorityQueue(Of TElement, TPriority) Frequent middle inserts LinkedList(Of T) O(1) at a node

ObservableCollection(Of T), BindingList(Of T) ReadOnlyCollection(Of T), IReadOnlyList(Of T)

ImmutableList, ImmutableDictionary, FrozenDictionary (.NET 8)

ConcurrentDictionary, ConcurrentQueue, ConcurrentBag, BlockingCollection

Dim stock As New Dictionary(Of String, Integer)(StringComparer.OrdinalIgnoreCase)
stock("PEN") = 10
stock("pen") += 5                               ' same key (case-insensitive comparer)
Dim qty As Integer
If stock.TryGetValue("Pen", qty) Then Console.WriteLine(qty)
Dim pq As New PriorityQueue(Of String, Integer)
pq.Enqueue("urgent", 1) : pq.Enqueue("later", 10)
Dim next1 = pq.Dequeue()

8.3 Exposing Collections Safely

Public Class Order
    Private ReadOnly _lines As New List(Of OrderLine)
    Public ReadOnly Property Lines As IReadOnlyList(Of OrderLine)
        Get
            Return _lines.AsReadOnly()
        End Get
    End Property
    Public Sub AddLine(line As OrderLine)
        ArgumentNullException.ThrowIfNull(line)
        _lines.Add(line)
    End Sub
End Class

8.4 Implementing Classic Data Structures

Practice exercises: a linked list, binary search tree, stack via an array, min-heap, graph with adjacency lists (BFS/DFS), LRU cache (Dictionary + LinkedList), trie.