VB.NET Collections
Collections provide a flexible way to store and manage groups of objects. They are part of the .NET Framework's powerful System.Collections namespace and its generic counterparts in System.Collections.Generic.
Using collections is essential for efficient data management in your VB.NET applications, allowing you to easily add, remove, search, and iterate over elements.
Key Concepts and Types
Non-Generic Collections (System.Collections)
These collections were part of earlier versions of the .NET Framework and store elements as Object
. While still functional, they require casting when retrieving elements and do not offer the compile-time type safety of generic collections.
- ArrayList: A dynamic array that grows as needed. Elements can be of any type.
- SortedList: A collection of key-value pairs that is sorted by key.
- Queue: A First-In, First-Out (FIFO) collection.
- Stack: A Last-In, First-Out (LIFO) collection.
- Hashtable: A collection of key-value pairs, optimized for fast lookup by key. Keys and values are stored as
Object
. - DictionaryBase: An abstract base class for custom dictionary collections.
Generic Collections (System.Collections.Generic)
Introduced with .NET Framework 2.0, generic collections provide type safety, better performance by avoiding boxing/unboxing, and improved code readability. They are the preferred choice for new development.
- List(Of T): A strongly-typed dynamic array.
T
represents the type of elements the list will hold (e.g.,List(Of String)
,List(Of Integer)
). - Dictionary(Of TKey, TValue): A strongly-typed collection of key-value pairs.
TKey
andTValue
specify the types of the keys and values, respectively. - Queue(Of T): A strongly-typed FIFO collection.
- Stack(Of T): A strongly-typed LIFO collection.
- SortedDictionary(Of TKey, TValue): A strongly-typed dictionary sorted by key.
- SortedList(Of TKey, TValue): A strongly-typed collection of key-value pairs sorted by key, with efficient access to both keys and values.
- LinkedList(Of T): A doubly linked list, allowing efficient insertion and deletion of elements anywhere in the list.
- HashSet(Of T): A collection that stores unique elements, with very fast membership testing and insertion.
Common Operations
Creating and Populating Collections
Here's how you might create and add elements to a generic List(Of String)
:
Imports System.Collections.Generic
Module CollectionExamples
Sub Main()
' Creating a List of Strings
Dim fruits As New List(Of String)()
' Adding elements
fruits.Add("Apple")
fruits.Add("Banana")
fruits.Add("Orange")
' Using Collection Initializer syntax (more concise)
Dim vegetables As New List(Of String) From {"Carrot", "Broccoli", "Spinach"}
' Creating a Dictionary of Integers and Strings
Dim productCodes As New Dictionary(Of Integer, String)()
productCodes.Add(101, "Laptop")
productCodes.Add(102, "Keyboard")
productCodes.Add(103, "Mouse")
Console.WriteLine("Fruits list created.")
Console.WriteLine("Products dictionary created.")
End Sub
End Module
Accessing and Iterating Through Collections
You can access elements by index (for lists) or by key (for dictionaries), or iterate through the entire collection.
For Each
loop is the most idiomatic way to iterate over collections in VB.NET.
' Iterating through the fruits list
For Each fruit As String In fruits
Console.WriteLine(fruit)
Next
' Accessing an element by index in the fruits list
Console.WriteLine("Second fruit: " & fruits(1)) ' Output: Second fruit: Banana
' Iterating through the productCodes dictionary
For Each kvp As KeyValuePair(Of Integer, String) In productCodes
Console.WriteLine($"Code: {kvp.Key}, Product: {kvp.Value}")
Next
' Accessing a value by key in the productCodes dictionary
If productCodes.ContainsKey(102) Then
Console.WriteLine("Product with code 102: " & productCodes(102)) ' Output: Product with code 102: Keyboard
End If
Removing Elements
Elements can be removed by their value or by their index/key.
' Removing an element by value from List(Of T)
fruits.Remove("Banana")
' Removing an element by key from Dictionary(Of TKey, TValue)
productCodes.Remove(103)
' Removing an element by index from List(Of T)
If fruits.Count > 0 Then
fruits.RemoveAt(0) ' Removes the first element
End If
Choosing the Right Collection
Collection Type | Primary Use Case | Performance Characteristics | Key Features |
---|---|---|---|
List(Of T) |
Ordered collection, frequent additions/removals at the end. | Fast add/remove at end, slow insert/remove in middle. Fast index-based access. | Type-safe, resizable array. |
Dictionary(Of TKey, TValue) |
Mapping keys to values, fast lookups by key. | Very fast add, remove, and lookup by key (average O(1)). | Type-safe key-value pairs, unique keys. |
Queue(Of T) |
Processing items in order of arrival (FIFO). | Fast enqueue and dequeue. | Type-safe FIFO buffer. |
Stack(Of T) |
Managing items with last-in, first-out order (LIFO). | Fast push and pop. | Type-safe LIFO buffer. |
SortedDictionary(Of TKey, TValue) |
Key-value mapping where keys must be kept sorted. | Balanced tree performance (O(log n) for most operations). | Type-safe, sorted key-value pairs. |
LinkedList(Of T) |
Frequent insertions or deletions anywhere in the sequence. | Fast insertion/deletion anywhere (O(1) if node is known), slow index access. | Type-safe, doubly linked list. |
HashSet(Of T) |
Storing unique items, checking for existence. | Very fast add, remove, and contains (average O(1)). | Type-safe, stores unique elements, unordered. |
System.Collections.Generic
) over non-generic ones (System.Collections
) for new development to ensure type safety and better performance.