0

I have a dictionary object like:

Dictionary<string, HashSet<int>> dict = new Dictionary<string, HashSet<int>>();
        dict.Add("foo", new HashSet<int>() { 15,12,16,18});
        dict.Add("boo", new HashSet<int>() { 16,47,45,21 });

I have to print in such a way such that result would be as following at each iteration:

It1: foo    boo  //only the key in a row
It2: 15     16
It3: 16     47

Can anyone help me to achieve this. Thanks.

mono
  • 1
  • 1
    Homework!! You need to study Console class. Here -> [ http://msdn.microsoft.com/en-us/library/system.console.aspx ] This will give you more ideas -> [ http://msdn.microsoft.com/en-us/library/system.console.setcursorposition.aspx ] – Nayan May 07 '10 at 08:12
  • Are you aware that neither `Dictionary` or `HashSet` guarantee to preserve the order of their elements? Your question/code seems to assume that they do. – LukeH May 07 '10 at 09:34

3 Answers3

1

First get the key: loop through all the dictionary keys and then get the values, for eg:

foreach(var v in dict.Keys)
{
Console.WriteLine(dict[v]);
}

Hope this helps.

24x7Programmer
  • 474
  • 5
  • 20
0

Here result is your dictionary and writer is a object of streamwriter

            int keyCount = results.Keys.Count;
            writer.WriteLine("<table border='1'>");
            writer.WriteLine("<tr>");
            for (int i = 0; i < keyCount; i++)
            {
                writer.WriteLine("<th>" + results.Keys.ToArray()[i] + "</th>");
            }
            writer.WriteLine("</tr>");

            int valueCount = results.Values.ToArray()[0].Count;
            for (int j = 0; j < valueCount; j++)
            {
                writer.WriteLine("<tr>");
                for (int i = 0; i < keyCount; i++)
                {
                    writer.WriteLine("<td>" + results.Values.ToArray()[i].ToArray()[j] + "</td>");
                }
                writer.WriteLine("</tr>");
            }
            writer.WriteLine("</table>");
Pritam Karmakar
  • 2,773
  • 5
  • 30
  • 49
  • The number of ToArray calls is insane. Each call is creating a new array from the items. For a large dictionary this would be very inefficient. – Cameron MacFarland May 07 '10 at 08:32
0

You should take the Tranpose() extension from here and test the following code:

Dictionary<string, HashSet<int>> dict = new Dictionary<string, HashSet<int>>();
dict.Add("foo", new HashSet<int>() { 15, 12, 16, 18 });
dict.Add("boo", new HashSet<int>() { 16, 47, 45, 21 });

var query = dict.Select(entry => entry.Value.Select(value => value.ToString()))
                .Transpose();

foreach (var key in dict.Keys)
{
    Console.Write(String.Format("{0,-5}", key));
}
Console.WriteLine();

foreach (var row in query)
{
    foreach (var item in row)
    {
        Console.Write(String.Format("{0,-5}", item));
    }
    Console.WriteLine();
}
Console.ReadKey();
Community
  • 1
  • 1
Oliver
  • 43,366
  • 8
  • 94
  • 151