Dictionary pivoting in C#

Niladri.Biswas
Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 2972
Given a dictionary object as under

 Dictionary<string, List<string>> dictContinents = new Dictionary<string, List<string>>();
dictStr.Add("Asia", new List<string>() { "India", "Pakistan", "Bangaladesh", "Singapore" });
dictStr.Add("Africa", new List<string>() { "Uganda", "Ghana","Ecuador" });
dictStr.Add("Europe", new List<string>() { "France", "Norway" , "Belgium" ,"Spain" });
dictStr.Add("South America", new List<string>() { "Argentina", "Bolivia" , "Brazil" ,"Uruguay", "Chile", "Colombia" });


We need to transpose the rows to columns.

Approach 1:

Dictionary<string, List<string>> dictContinents = new Dictionary<string, List<string>>();
dictContinents.Add("Asia", new List<string>() { "India", "Pakistan", "Bangaladesh", "Singapore" });
dictContinents.Add("Africa", new List<string>() { "Uganda", "Ghana", "Ecuador","Somalia" });
dictContinents.Add("Europe", new List<string>() { "France", "Norway", "Belgium", "Spain" });
dictContinents.Add("South America", new List<string>() { "Chile", "Bolivia", "Brazil", "Peru" });

Enumerable.Range(0, dictContinents.Values.First().Count)
.ToList()
.ForEach(i => Console.WriteLine(string.Join(" ", dictContinents.Values.Select(values => values[i]))));


Approach 2:

Dictionary<string, List<string>> dictContinents = new Dictionary<string, List<string>>();
dictContinents.Add("Asia", new List<string>() { "India", "Pakistan", "Bangaladesh", "Singapore" });
dictContinents.Add("Africa", new List<string>() { "Uganda", "Ghana", "Ecuador","Somalia" });
dictContinents.Add("Europe", new List<string>() { "France", "Norway", "Belgium", "Spain" });
dictContinents.Add("South America", new List<string>() { "Chile", "Bolivia", "Brazil", "Peru" });

int maxLimit = dictContinents.Values.First().Count;
//or dictContinents.Values.Select(l => l.Count).Max();
//or dictContinents.Values.Count

for (int i = 0; i < maxLimit; i++)
{
StringBuilder sb = new StringBuilder();
string space = string.Empty;
dictContinents.Keys.ToList().ForEach(k =>
{
sb.AppendFormat("{0}{1}", space, dictContinents[k][i]);
space = " ";
});

Console.WriteLine(sb.ToString());
}


Output

India            Uganda    France  Chile
Pakistan Ghana Norway Bolivia
Bangaladesh Ecuador Belgium Brazil
Singapore Somalia Spain Peru



Hope this helps

Comments or Responses

Login to post response