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"}
}
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access