2011-06-23 123 views
32

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

+0

你知道的类型编译时或运行时的'Dictionary'元素? –

+0

HashTable的所有对象(键和值)都可以转换为将用作Dictionary的通用参数的特定目标类型?或者你是否愿意排除HashTable中不适合的类型? – daveaglick

+0

如果可能的话,你应该把对象放在一个'Dictionary'开始。 'HashTable'类自从引入'Dictionary'后实际上已经过时了。由于'Dictionary'是'HashTable'的通用替代品,因此代码需要稍微调整以使用'Dictionary'代替。 – Guffa

回答

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

感谢您转换为字典并将键和值转换为给定类型的完整答案。 – RKP

8
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

的遗留应用程序,谢谢你的解决方案,它不需要循环,这正是我正在寻找的。然而,我接受另一个解决方案作为答案,因为它会执行更正类型的转换,并为其定义扩展方法。上面的那个返回key和value的通用对象类型,这与hashtable没有任何其他的优势。 – RKP

3

你也可以创建代理-J的回答是

Dictionary<KeyType, ItemType> d = new Dictionary<KeyType, ItemType>(); 
foreach (var key in hashtable.Keys) 
{ 
d.Add((KeyType)key, (ItemType)hashtable[key]); 
} 
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()); 
    } 
2

扩展方法版本的扩展方法:

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); 
    } 
}