Collections and Generic Collections

12.1 List(Of T)

Dim fruits As New List(Of String) From {"apple", "banana"}    ' collection initializer
fruits.Add("cherry")
fruits.AddRange({"date", "elderberry"})
fruits.Insert(0, "apricot")
fruits.Remove("banana")
fruits.RemoveAt(0)
fruits.RemoveAll(Function(f) f.StartsWith("e"))
Console.WriteLine(fruits.Count & " " & fruits(0) & " " & fruits.Contains("cherry"))
fruits.Sort()
fruits.Reverse()
Dim idx = fruits.IndexOf("cherry")
Dim longOnes = fruits.FindAll(Function(f) f.Length > 5)
fruits.ForEach(Sub(f) Console.WriteLine(f))
Dim arr = fruits.ToArray()
fruits.Clear()

12.2 Dictionary(Of TKey, TValue)

Dim ages As New Dictionary(Of String, Integer) From {
    {"Ana", 30},
    {"Bo", 25}
}
ages("Cy") = 40                        ' add or update
ages.Add("Dee", 22)                    ' throws if the key exists
ages.TryAdd("Dee", 99)                 ' False, no exception
Dim age As Integer
If ages.TryGetValue("Ana", age) Then Console.WriteLine(age)
Console.WriteLine(ages.ContainsKey("Bo"))
ages.Remove("Bo")
For Each pair In ages
    Console.WriteLine($"{pair.Key}: {pair.Value}")
Next
Dim names = ages.Keys.ToList()
Dim total = ages.Values.Sum()
Dim ci As New Dictionary(Of String, Integer)(StringComparer.OrdinalIgnoreCase)   ' case-insensitive keys

12.3 Other Generic Collections

HashSet(Of T) Unique items, fast lookup, set operations SortedSet(Of T) Sorted unique items FIFO (Enqueue, Dequeue, Peek) LIFO (Push, Pop, Peek) LinkedList(Of T) Doubly linked list

SortedDictionary(Of K, V) / SortedList(Of K, V) PriorityQueue(Of TElement, TPriority) (.NET 6+) ObservableCollection(Of T) Notifies UI of changes (WPF)

ReadOnlyCollection(Of T) / ImmutableList(Of T) Read-only / immutable

ConcurrentDictionary, ConcurrentQueue, BlockingCollection

Dim unique As New HashSet(Of Integer) From {1, 2, 3}
unique.Add(2)                                  ' ignored (returns False)
unique.UnionWith({4, 5}) : unique.IntersectWith({1, 4, 9})
Dim q As New Queue(Of String)
q.Enqueue("first") : q.Enqueue("second")
Console.WriteLine(q.Dequeue())
Dim st As New Stack(Of Integer)
st.Push(1) : st.Push(2)
Console.WriteLine(st.Pop())
Dim pq As New PriorityQueue(Of String, Integer)()
pq.Enqueue("low", 5) : pq.Enqueue("high", 1)
Console.WriteLine(pq.Dequeue())                ' "high"

12.4 Legacy Collections

ArrayList, Hashtable (non-generic, Object-based: avoid them in new code).

The VB Collection object (Microsoft.VisualBasic.Collection): 1-based, key/value, from VB6 heritage.

Dim col As New Collection()
col.Add("Ana", "k1")
Console.WriteLine(col("k1") & " " & col(1))