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 an开发者_如何转开发yone help me to achieve this. Thanks.
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.
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>");
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();
精彩评论