Home
Map
Convert Dictionary to StringTransform a Dictionary into a string with StringBuilder, and get a Dictionary from a string again.
C#
This page was last reviewed on Nov 26, 2023.
Convert Dictionary, string. A C# Dictionary can be converted to string format. This string can then be persisted in a text file and read back into memory.
Dictionary
Dictionary Binary File
Shows a string dictionary
Notes, round trip. With 2 methods, we can round-trip the Dictionary and string. A method like GetDict() can be used in many places in a program.
An example. We write the values of Dictionary types to the disk and then parse them. I had to store a Dictionary of string keys and int values. This is also called serialization.
Step 1 We call GetLine. This method receives a Dictionary that was declared at class-level.
Step 2 GetLine() iterates through the Dictionary's KeyValuePair collection. It appends the data to a StringBuilder.
foreach
KeyValuePair
Step 3 We write the string data we generated from the Dictionary to a file. The "dict.txt" file is used.
Step 4 We must get a new Dictionary from the file we saved it to. GetDict here does that for us.
Step 5 We parse in the dictionary from a string with split(). The string has commas and semicolons as separators.
String Split
Shows a string dictionary
using System; using System.Collections.Generic; using System.IO; using System.Text; class Program { static void Main() { var data = new Dictionary<string, int>() { { "salmon", 5 }, { "tuna", 6 }, { "clam", 2 }, { "asparagus", 3 } }; // Step 1: get string from Dictionary. string value = GetLine(data); // Step 3: save to disk. File.WriteAllText("dict.txt", value); // Step 4: get dictionary again. var result = GetDict("dict.txt"); foreach (var pair in result) { Console.WriteLine("PAIR: " + pair); } } static string GetLine(Dictionary<string, int> data) { // Step 2: build up the string data. StringBuilder builder = new StringBuilder(); foreach (var pair in data) { builder.Append(pair.Key).Append( ":").Append(pair.Value).Append(','); } string result = builder.ToString(); // Remove the end comma. result = result.TrimEnd(','); return result; } static Dictionary<string, int> GetDict(string file) { // Step 5: parse in the dictionary from a string. var result = new Dictionary<string, int>(); string value = File.ReadAllText(file); // Split the string. string[] tokens = value.Split(new char[] { ':', ',' }, StringSplitOptions.RemoveEmptyEntries); // Build up our dictionary from the string. for (int i = 0; i < tokens.Length; i += 2) { string name = tokens[i]; string freq = tokens[i + 1]; // Parse the int. int count = int.Parse(freq); // Add the value to our dictionary. result[name] = count; } return result; } }
PAIR: [salmon, 5] PAIR: [tuna, 6] PAIR: [clam, 2] PAIR: [asparagus, 3]
Exceptions. Whenever you deal with the file system, your input may become corrupted. If your code is not critical, it is worthwhile to try to recover from any errors.
Exception
Summary. We persisted the Dictionary to the disk and read it back in from the file. You can sometimes develop custom methods to do this with the best performance.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 26, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.