散列表中的foreach项

时间:2015-05-12 11:43:28

标签: c# hashtable

我需要使用Hastable(不是List而不是Dictionary),而且我有许多带键的变量。我将键和变量添加到类中,并在我的程序中使用它。但我不知道如何解析Hashtable。我试过这个:

        Hashtable toboofer = null;

        string path = @"my.bin";

        FileStream fin = File.OpenRead(path);

        try
        {
            BinaryFormatter bf = new BinaryFormatter();

            toboofer = (Hashtable)bf.Deserialize(fin);

            for (int i = 0; i <= toboofer.Count; i++ )
                //foreach (KeyValuePair<string, string> kvp in toboofer)
                {
                    myclass cl = new myclass();
                    cl.Fio = toboofer[i].ToString();
                    cl.About = toboofer[i].ToString();
                }
        }

但我有错误。当我尝试string item或循环for时,我也有错误。

2 个答案:

答案 0 :(得分:2)

HashtableDictionaryEntry作为集合元素

foreach (DictionaryEntry entry in toboofer)
{
    // do something
}

从哈希表中列出myclass

var listOfMyClass = toboofer.Cast<DictionaryEntry>().
                             Select(e => new myclass() 
               { Fio = e.Key.ToString(), About = e.Value.ToString() });

答案 1 :(得分:0)

尝试这个哈希表使用如果是DictionaryEntry,其中KeyValuePair泛型由泛型字典.Net 2(及以后)使用

请注意,Hashtable没有它的泛型版本,而hastable中的每个元素都由DictionaryEntry表示

foreach (DictionaryEntry entry in hashtable)
    {
        Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
    }
相关问题