在C#中将HashTable转换为Dictionary

时间:2011-06-23 14:34:46

标签: c# .net generics dictionary hashtable

如何在C#中将HashTable转换为Dictionary?可能吗?例如,如果我在HashTable中有对象集合,并且如果我想将其转换为具有特定类型的对象的字典,那该怎么做?

5 个答案:

答案 0 :(得分:60)

public static Dictionary<K,V> HashtableToDictionary<K,V> (Hashtable table)
{
   return table
     .Cast<DictionaryEntry> ()
     .ToDictionary (kvp => (K)kvp.Key, kvp => (V)kvp.Value);
}

答案 1 :(得分:9)

var table = new Hashtable();

table.Add(1, "a");
table.Add(2, "b");
table.Add(3, "c");


var dict = table.Cast<DictionaryEntry>().ToDictionary(d => d.Key, d => d.Value);

答案 2 :(得分:3)

您也可以为该

创建扩展方法
Dictionary<KeyType, ItemType> d = new Dictionary<KeyType, ItemType>();
foreach (var key in hashtable.Keys)
{
 d.Add((KeyType)key, (ItemType)hashtable[key]);
}

答案 3 :(得分:2)

代理-j的答案的扩展方法版本:

using System.Collections;
using System.Collections.Generic;
using System.Linq;

public static class Extensions {

    public static Dictionary<K,V> ToDictionary<K,V> (this Hashtable table)
    {
       return table
         .Cast<DictionaryEntry> ()
         .ToDictionary (kvp => (K)kvp.Key, kvp => (V)kvp.Value);
    }
}

答案 4 :(得分:0)

    Hashtable openWith = new Hashtable();
    Dictionary<string, string> dictionary = new Dictionary<string, string>();

    // Add some elements to the hash table. There are no 
    // duplicate keys, but some of the values are duplicates.
    openWith.Add("txt", "notepad.exe");
    openWith.Add("bmp", "paint.exe");
    openWith.Add("dib", "paint.exe");
    openWith.Add("rtf", "wordpad.exe");

    foreach (string key in openWith.Keys)
    {
        dictionary.Add(key, openWith[key].ToString());
    }