C# 如何打印哈希表的内容?
我有一个哈希表,详细信息如下所述C# 如何打印哈希表的内容?,c#,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) {
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 (var sublist in result)
{
foreach (var obj in sublist)
{
Console.WriteLine(obj);
}
}
我不知道您希望如何格式化输出,但要打印列表的内容,您必须对其进行迭代
在列表列表上,您需要迭代两次
也许解决办法是:
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);
}
}
}
public void获取唯一序列(列表名称、列表名称序列)
{
Hashtable test=新的Hashtable();
添加(名称顺序、名称);
foreach(字典输入测试条目)
{
string key=string.Empty;
foreach(列表entry.Key中的字符串s)
{
键+=s+“”;
}
foreach(列表项中的列表。值)
{
字符串值=string.Empty;
foreach(列表中的字符串s)
{
值+=s+“”;
}
WriteLine(“{0}:{1}”,键,值);
}
}
}
当然,您需要根据需要格式化输出。您可能不希望在哈希表中插入列表对象,而是希望在列表中插入元素
因此,首先你必须做一些事情,比如:
(假设列表不为空且大小相同)
然后,您的方法应该可以工作。您必须将键和值强制转换为列表
,然后迭代它们以打印它们。列表的ToString()
是“System.Collections.Generic.List`1[T]”这个代码在我看来很奇怪。我可以看到任何可以使用列表作为键的场景。您到底想实现什么?哈希表
从.NET 2.0开始就被有效地贬值了。您应该改用字典
。我尝试了上面的代码,但收到了错误消息:foreach语句无法对“object”类型的变量进行操作,因为“object”不包含“GetEnumerator”的公共定义@dexter这只是一个猜测,因为我看不到您的代码,但是您需要将对象强制转换回列表
,然后才能对其调用foreach
。塞尔曼在他的博文中这样做:foreach(在((List)entry.Value中的字符串y)。选择many(x=>x))
但使用LINQ来减少必要的循环数。在我们的例子中,相关的部分是强制转换。我尝试了Selman的代码,但值出现了异常:无法将类型为“System.String”的对象强制转换为类型为“System.Collections.Generic.List1[System.Collections.Generic.List
1[System.String]]'。@dexter您需要编辑OP并显示所引用的代码。用这种方法很难找出你做错了什么。
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);
}
}
}
for(int i =0;i<name.Count;i++){
test.Add(nameSequence[i], name[i]);
}
test.Add(nameSequence, name);