TheDeveloperBlog.com


C# Convert Dictionary to String

Convert dictionary, string. A Dictionary can be converted to string format. This string can then be persisted in a text file and read back into memory. A new Dictionary instance is then constructed. Both the keys and the values are persisted.


Example. Here we look at a simple way you can 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.

Tip: There are advanced methods in .NET you can use. However, if you want exact control, my method may be best.

Based on:

.NET 4

Class that uses disk Dictionary: C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

class ConvertDictionary
{
    Dictionary<string, int> _dictionary = new Dictionary<string, int>()
    {
	{"salmon", 5},
	{"tuna", 6},
	{"clam", 2},
	{"asparagus", 3}
    };

    public ConvertDictionary()
    {
	// Convert dictionary to string and save
	string s = GetLine(_dictionary);
	File.WriteAllText("dict.txt", s);
	// Get dictionary from that file
	Dictionary<string, int> d = GetDict("dict.txt");
    }

    string GetLine(Dictionary<string, int> d)
    {
	// Build up each line one-by-one and then trim the end
	StringBuilder builder = new StringBuilder();
	foreach (KeyValuePair<string, int> pair in d)
	{
	    builder.Append(pair.Key).Append(":").Append(pair.Value).Append(',');
	}
	string result = builder.ToString();
	// Remove the final delimiter
	result = result.TrimEnd(',');
	return result;
    }

    Dictionary<string, int> GetDict(string f)
    {
	Dictionary<string, int> d = new Dictionary<string, int>();
	string s = File.ReadAllText(f);
	// Divide all pairs (remove empty strings)
	string[] tokens = s.Split(new char[] { ':', ',' },
	    StringSplitOptions.RemoveEmptyEntries);
	// Walk through each item
	for (int i = 0; i < tokens.Length; i += 2)
	{
	    string name = tokens[i];
	    string freq = tokens[i + 1];

	    // Parse the int (this can throw)
	    int count = int.Parse(freq);
	    // Fill the value in the sorted dictionary
	    if (d.ContainsKey(name))
	    {
		d[name] += count;
	    }
	    else
	    {
		d.Add(name, count);
	    }
	}
	return d;
    }
}

In the example, we receive a string from the Dictionary<string, int>. It is up to you to write this to the text file. The GetLine method receives a Dictionary that was declared at class-level.

GetLine declares a new StringBuilder, which helps performance here. Next, it iterates through the Dictionary's KeyValuePair collection. The Append calls are chained, which also improves performance.

Tip: Semicolons separate the two parts of each pair, and commas separate the pairs.

KeyValuePair

Next, we must get a new Dictionary<string, int> from the file we saved it to. GetDict here does that for us. First, it declares the Dictionary it will return. It reads in the specified file with .NET file handling.

File

Split. The string has both commas and semicolons that separate parts. We split on both characters and then consume two results in each loop iteration. We use ContainsKey and Add on the Dictionary we are building. This reliably works.

Split

Exceptions. This code will crash but that's not my fault. Whenever you deal with the file system, your input may become corrupted. It will fail. So deal with as best you can with exceptions. The two calls above should be wrapped in exceptions.

Recover from errors. Whenever you deal with the file system and your code is not critical, try to recover from any errors. Recover by returning an error string, blank string, or just doing nothing.

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. This method is easily extended to other languages.