Freitag, 17. April 2015

Flatten dictionary to string

Problem:
How to save the content of a dictionary into a string?

Solution:

Dictionary<string, string> testDic = new Dictionary<string, string>();
testDic.Add("key1", "value1");
testDic.Add("key2", "value2");
testDic.Add("key3", "value3");

// flatten dictionary
string resultStr = string.Join(";", testDic.Select(y => y.Key + "=" + y.Value));

// reverse
Dictionary<string, string> resultDic = resultStr.Split(';').Select(x => x.Split('=')).ToDictionary(x => x[0], y => y[1]);


             
How to do it with a nested dictionary?

Solution:
Dictionary<string, Dictionary<string, double>> testDic = new Dictionary<string, Dictionary<string, double>>();

testDic.Add("key1", new Dictionary<string, double>());
testDic["key1"].Add("key11", 11);
testDic.Add("key2", new Dictionary<string, double>());
testDic["key2"].Add("key21", 21);
testDic["key2"].Add("key22", 22);
testDic.Add("key3", new Dictionary<string, double>());
testDic["key3"].Add("key31", 31);

// flatten dictionary
string resultStr = string.Join("|", testDic.Select(x => x.Key + ":" + string.Join(";", testDic[x.Key].Select(y => y.Key + "=" + y.Value))));

// reverse
Dictionary<string, Dictionary<string, double>> resultDic = new Dictionary<string, Dictionary<string, double>>();
Dictionary<string, string> tmpDic = resultStr.Split('|').Select(x => x.Split(':')).ToDictionary(x => x[0], y => y[1]);
tmpDic.ToList().ForEach(t => resultDic.Add(t.Key, t.Value.Split(';').Select(x => x.Split('=')).ToDictionary(x => x[0], y => Convert.ToDouble(y[1]))));