INITIALIZING COLLECTIONS

Collection classes that provide an Add method such as List, Dictionary, and SortedDictionary have their own initialization syntax. Instead of using an equals sign as you would with an array initializer, use the From keyword followed by the values that should be added to the collection surrounded by curly braces.

For example, the following code initializes a new List(Of String):

Dim pies As New List(Of String) From
    {
        "Apple", "Banana", "Cherry", "Coconut Cream"
    }

The items inside the braces must include all of the values needed by the collection’s Add method. For example, the Dictionary class’s Add method takes two parameters giving the key and value that should be added so each entry in the initializer should include a key and value.

The following code initializes a Dictionary(Of String, String). The parameters to the class’s Add method are an item’s key and value so, for example, the value 940-283-1298 has the key Alice Artz. Later you could look up Alice’s phone number by searching the Dictionary for the item with key “Alice Artz.”

Dim phone_numbers As New Dictionary(Of String, String) From
    {
        {"Alice Artz", "940-283-1298"},
        {"Bill Bland", "940-237-3827"},
        {"Carla Careful", "940-237-1983"}
    }
ADDING ADD
Some collection classes such as Stack and Queue don’t have an Add method, so From won’t work for them. Fortunately, you can use extension methods (described in the “Extension Methods” section in Chapter 16, “Subroutines and Functions”) to add one. The ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.