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}")
NextExplanation
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
Variables and Types
Declare variables with Dim and type inference.
Loops and Iteration
For, For Each, While, and Do loops in VB.
Sub and Function Procedures
Define Sub (no return) and Function (returns value).
Windows Forms Basics
Create a simple WinForms application.
File I/O
Read/write text files and use My.Computer.FileSystem.
Error Handling (Try/Catch)
Structured exception handling in VB.