Convert Dictionary, String. With a custom VB.NET function, it is possible to convert a Dictionary into a String. And then the String can be persisted to a file.
Though other approaches are possible, such as JSON or binary encoding, the String code here is occasionally useful. It is simple, the output file is human-readable.
Example. This program performs 2 main tasks: it converts a Dictionary to a String, and then a String into a Dictionary. It also stores the data in a text file.
Step 1 We create a Dictionary, and then add 4 String keys along with 4 Integer values.
Step 2 We convert the Dictionary into a String by looping over its values with For Each, and appending to a StringBuilder.
Imports System.IO
Imports System.Text
Module Module1
Sub Main(args as String())
' Step 1: create a Dictionary.
Dim data = New Dictionary(Of String, Integer)()
data.Add("bird", 2)
data.Add("frog", 1)
data.Add("dog", 20)
data.Add("rabbit", 3)
' Step 2: convert Dictionary to string and write it to the disk.
Dim line = GetLine(data)
File.WriteAllText("dict.txt", line)
' Step 3: convert string from file into Dictionary and loop over it.
Dim result = GetDict("dict.txt")
For Each pair in result
Console.WriteLine($"PAIR: {pair}")
Next
End Sub
Function GetLine(data As Dictionary(Of String, Integer)) As String
' Use StringBuilder to create a string containing pairs.
Dim builder = New StringBuilder()
For Each pair in data
builder.Append(pair.Key).Append( ":").Append(pair.Value).Append(",")
Next
' Remove end comma.
Dim result = builder.ToString()
result = result.TrimEnd(","c)
Return result
End Function
Function GetDict(path As String) As Dictionary(Of String, Integer)
' Read in file, and Split it.
Dim result = New Dictionary(Of String, Integer)()
Dim value = File.ReadAllText(path)
Dim tokens = value.Split(New Char() { ":"c, ","c }, StringSplitOptions.RemoveEmptyEntries)
For i = 0 To tokens.Length - 1
' Get name and value from this position, and store it in the Dictionary.
Dim name = tokens(i)
Dim freq = tokens(i + 1)
Dim count = Integer.Parse(freq)
result(name) = count
i += 1
Next
Return result
End Function
End ModulePAIR: [bird, 2]
PAIR: [frog, 1]
PAIR: [dog, 20]
PAIR: [rabbit, 3]
Summary. It is possible to generate String data from a Dictionary's contents by looping over it with For Each. Then we can load the file, Split it, and create a Dictionary from it.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.