【问题标题】:How to print contents of an hash table?如何打印哈希表的内容?
【发布时间】:2014-04-02 20:16:00
【问题描述】:

我有一个哈希表,详细信息如下所述

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]

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

【问题讨论】:

  • 您必须将键和值转换为 List&lt;string&gt; 并遍历它们以打印它们。 List&lt;T&gt;ToString() 是“System.Collections.Generic.List`1[T]”
  • 这段代码在我看来很奇怪。我几乎看不到任何可以使用列表作为键的场景。你到底想达到什么目的?
  • HashTable 自 .NET 2.0 起有效折旧。您应该改用Dictionary

标签: c#


【解决方案1】:

您可能不想在哈希表中插入列表对象,而是在列表中插入元素。

因此,首先您必须执行以下操作: (假设列表不为空且大小相同)

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

代替:

   test.Add(nameSequence, name);

然后你的方法应该有效。

【讨论】:

    【解决方案2】:

    我不知道您想如何格式化输出,但要打印 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);
            }
        }
    }
    

    当然,你需要根据自己的需要来格式化输出。

    【讨论】:

      【解决方案3】:

      嗯,问题不在于打印哈希表。这是关于打印List&lt;List&lt;string&gt;&gt;

      您希望每个键和值都像这样:

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

      【讨论】:

      • 我尝试了上面的代码,但收到错误消息:foreach 语句无法对“object”类型的变量进行操作,因为“object”不包含“GetEnumerator”的公共定义
      • @dexter 这只是一个猜测,因为我看不到您的代码,但您需要将对象转换回List&lt;List&lt;string&gt;&gt;,然后才能调用foreach。 Selman 在他的帖子中做到了这一点:foreach (string y in ((List&lt;List&lt;string&gt;&gt;)entry.Value).SelectMany(x =&gt; x)),但使用 LINQ 来减少必要的循环数。在我们的例子中,相关的部分是铸造。
      • 我尝试了 Selman 的代码,但值出现异常:无法将“System.String”类型的对象转换为“System.Collections.Generic.List1[System.Collections.Generic.List1[System.Stri” ​ng]]'.
      • @dexter 您需要编辑您的 OP 并显示您所指的代码。通过这种方式很难弄清楚你做错了什么。
      猜你喜欢
      • 2013-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-19
      • 1970-01-01
      • 2015-07-16
      • 2017-08-16
      • 1970-01-01
      相关资源
      最近更新 更多