如何打印哈希表的内容?

时间:2014-04-02 20:16:00

标签: c#

我的哈希表中包含如下所述的详细信息

public void get_Unique_Sequence(List<string> name, List<List<string>> nameSequence)
{
     Hashtable test = new Hashtable();

     test.Add(nameSequence, name)

     foreach (DictionaryEntry entry in test)
     {
         Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
     }
}

我试图在foreach循环的帮助下打印哈希表的内容。然而,我得到的输出是

输出:

System.Collections.Generic.List`1[System.String]: System.Collections.Generic.List`1[System.String]

请指导我获取哈希表的密钥和值(即内容)。

3 个答案:

答案 0 :(得分:1)

我不知道你想如何格式化输出,但要打印你必须迭代的List的内容。

在列表列表中,您需要迭代两次。

也许解决方案可能是这样的:

public void get_Unique_Sequence(List<string> name, List<List<string>> nameSequence)
{
    Hashtable test = new Hashtable();

    test.Add(nameSequence, name);

    foreach (DictionaryEntry entry in test)
    {
        string key = string.Empty;

        foreach (string s in (List<string>)entry.Key)
        {
            key += s + " "; 
        }

        foreach (List<string> list in (List<List<string>>)entry.Value)
        {
            string value = string.Empty;
            foreach (string s in list)
            {
                value += s + " ";
            }

            Console.WriteLine("{0}: {1}", key, value);
        }
    }
}

当然,您需要根据需要格式化输出。

答案 1 :(得分:1)

您可能不希望在哈希表中插入列表对象,但是列表中的元素。

首先你要做的事情如下: (假设列表不为空并且具有相同的大小)

   for(int i =0;i<name.Count;i++){
       test.Add(nameSequence[i], name[i]);
   }

instad of:

   test.Add(nameSequence, name);

然后你的方法应该有效。

答案 2 :(得分:0)

嗯,问题不在于打印哈希表。它是关于打印List<List<string>>

对于每个键和值,您需要这样的东西:

foreach (var sublist in result)
{
    foreach (var obj in sublist)
    {
        Console.WriteLine(obj);
    }
}