2011-06-23 48 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); 
    } 
}