Skip to content
Visual Basic

Collections (List, Dictionary)

Generic collections in VB.NET.

By EZ4Code Team
listdictionarylinq

Code

' List(Of T)
Dim nums As New List(Of Integer) From {1, 2, 3}
nums.Add(4)
nums.AddRange({5, 6})
nums.Remove(3)
Dim first As Integer = nums(0)
Dim count As Integer = nums.Count

' Dictionary
Dim ages As New Dictionary(Of String, Integer) From {
    {"Alice", 30}, {"Bob", 25}
}
ages("Carol") = 28
If ages.ContainsKey("Alice") Then
    Console.WriteLine(ages("Alice"))
End If

' LINQ
Dim evens = From n In nums Where n Mod 2 = 0 Select n
Dim squares = nums.Select(Function(n) n * n).ToList()
Dim sum As Integer = nums.Sum()
Dim grouped = nums.GroupBy(Function(n) n Mod 2)

' For Each over dictionary
For Each kvp In ages
    Console.WriteLine($"{kvp.Key}: {kvp.Value}")
Next

Explanation

List(Of T) is the dynamic array; Dictionary(Of TKey, TValue) is the hash map. From {…} is VB's collection initializer. LINQ works the same as in C# — both query syntax (From…Where…Select) and method syntax (.Select/.Where). Use generic collections over ArrayList/Hashtable (deprecated).

More Visual Basic Snippets