迭代HashTable中的列表 [英] To iterate the list in HashTable

查看:68
本文介绍了迭代HashTable中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在以下情况下使用了哈希表.

100山姆
100约翰

由于哈希表键是多余的,我们不能再加100.所以我使用了如下列表.

Hi

I have used hashtable for the following scenario.

100 Sam
100 John

Since hash table key is unqiue we cannot add 100 again . So i used a list as follows .

List<string> List = new List<string>();
list.add(sam)
list.add(John)

hashtable ht = new Hashtable()
ht.add(100,list) 


现在,我该如何迭代&显示输出中的值,如图所示?

100山姆
约翰

在此先感谢


Now how do I iterate & display the values in output as shown?

100 Sam
John

Thanks in advance

推荐答案

在新开发中切勿使用Hashtable或任何其他非通用集合.在引入泛型时,早在.NET Framework v.2.0时,它们就被一组泛型类型所取代.由于需要类型转换,因此非通用的非专业化集合很糟糕.

System.Collection.Generic.DictionarySystem.Collection.Generic.SortedDictionarySystem.Collection.Generic.SortedList中选择;它们之间的主要区别在于冗余和性能之间的折衷.

请参阅 http://msdn.microsoft.com/en-us/library/system. collections.generic.aspx [ ^ ].

您的问题将如下所示:
You should never use Hashtable or any other non-generic collections in new development. They are superseded by a set of generic types as early as of .NET Framework v.2.0, when generics were introduced. Non-generic non-specialized collections are bad due to a need for type casts.

Choose from System.Collection.Generic.Dictionary, System.Collection.Generic.SortedDictionary or System.Collection.Generic.SortedList; they differ mostly in different trade-off between redundancy and performance.

Please see http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx[^].

You problem will look like this:
using IntIndexedStringDictionary = Dictionary<int, string>;
using Pair = KeyValuePair<int, string>;

//...

IntIndexedStringDictionary dictionary = new IntIndexedStringDictionary();
dictionary.Add(1, "first");
dictionary.Add(3, "third");
//...

foreach (Pair pair in dictionary) {
    int key = pair.Key;
    string value = pair.Value;
    //...
}



—SA



—SA


您可以这样做;

You could do it like this;

IList<string> list = new List<string>();
list.Add("Sam");
list.Add("John");

Hashtable ht = new Hashtable();
ht.Add(100, list);

foreach (object key in ht.Keys)
{
    Console.Write("{0} ", key);
    foreach (string name in (IList<string>)ht[key])
    {
        Console.WriteLine(name);
    }
}



尽管我建议使用System.Collection.Generic中的IDictionaryDictionary而不是哈希表.

希望这会有所帮助,
弗雷德里克(Fredrik)



Although I recommend using IDictionary and Dictionary from System.Collection.Generic instead of hashtable.

Hope this helps,
Fredrik


这篇关于迭代HashTable中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆