Dictionaries in Visual Basic
Key-value stores with TryGetValue, the lookup that cannot throw.
Dim stock As New Dictionary(Of String, Integer) From {
{"flour", 12}, {"sugar", 5}
}
stock("yeast") = 9
stock("sugar") += 3
If stock.ContainsKey("flour") Then Console.WriteLine("flour on hand")
Dim salt As Integer
If Not stock.TryGetValue("salt", salt) Then salt = 0
Console.WriteLine($"salt jars: {salt}")
For Each pair In stock
Console.WriteLine($"{pair.Key,-8} {pair.Value,3}")
Next
How it works
From {{...}}pairs keys with values at construction.- Assigning to a missing key adds it;
+=updates in place. TryGetValuefills a variable and reports success as Boolean.For Each pairwalks KeyValuePairs with.Keyand.Value.
Keywords and builtins used here
DimEachForIfIntegerNewNextNotOfStringThen
The run, in numbers
- Lines
- 15
- Characters to type
- 388
- Tokens
- 107
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 76 seconds.
Step 3 of 3 in Collections, step 6 of 29 in Language basics.