Array Class Collections File String Console Data Directive Enum Exception If Interface Lambda Loop Nothing Number Process Property Regex Sort StringBuilder Structure Sub Time Windows
A collection is an object. It contains references to other objects. In this way VB.NET combines many class instances and values together. With collections we construct object models that mirror real-world problems.
You often need to store many elements in a resizable array. You might not even know how many elements are needed when you begin. The List and ArrayList types are excellent for programs with this requirement. The List type is best.List List Find BinarySearch ArrayList
Problem that creates List: VB.NET Module Module1 Sub Main() ' Create List. Dim list As List(Of String) = New List(Of String) list.Add("dot") list.Add("perls") list.Add("net") ' Sort List. list.Sort() ' Display sorted List contents. Console.WriteLine(String.Join(" ", list)) End Sub End Module Output dot net perls
This program creates a List of three String literals.
It then sorts them alphabetically.
It uses String.Join to combine them.
The program displays "dot net perls".
The three words are arranged alphabetically, A to Z.
If you have a large collection of elements and want to find one fast, the Dictionary type presents an ideal solution. You can perform lookups on the Dictionary instance. You can also use the Hashtable type for a similar effect.Dictionary Dictionary Sort ToDictionary TryGetValue KeyValuePair HashTable
Program that uses Dictionary: VB.NET Module Module1 Sub Main() ' Create Dictionary. Dim dict As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer) dict.Add("dot", 1) dict.Add("net", 2) dict.Add("perls", 3) ' Lookups. Console.WriteLine(dict("dot")) Console.WriteLine(dict("net")) Console.WriteLine(dict("perls")) End Sub End Module Output 1 2 3
The program creates a Dictionary with String keys—and Integer values at each key. It adds "dot" with the value 1. It then adds two other key-value pairs. It then looks up the three keys and prints their values.
There are other collection types available for use in your VB.NET programs. Some of these—such as the HashSet and Tuple types—are generics. They can be used to simplify certain problems.HashSet Queue Stack Tuple
Converting collections requires knowledge of what functions are available in the .NET Framework. We elaborate upon conversions in the VB.NET programming language. Sometimes, custom methods are required.ToArray ToList ArrayList to Array Dictionary to List List to Array
Collections are useful in nearly every VB.NET program. The built-in collections found in the .NET Framework are powerful, fast and complete. And the most modern ones are located in System.Collections.Generic.