行Wise迭代字典对象

时间:2010-05-07 08:05:49

标签: c# data-structures

我有一个字典对象,如:

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 });

我必须以这样的方式打印,以便在每次迭代时结果如下:

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

任何人都可以帮助我实现这一目标。感谢。

3 个答案:

答案 0 :(得分:1)

首先获取密钥:遍历所有字典键,然后获取值,例如:

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

希望这有帮助。

答案 1 :(得分:0)

这里的结果是你的字典和作家是节选者的对象

            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>");

答案 2 :(得分:0)

您应该使用Tranpose()扩展名from here并测试以下代码:

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();