2013-12-16 56 views
2

我想轉換一個哈希表來disctionary,發現了一個問題在這裏: convert HashTable to Dictionary in C#哈希表,以字典

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

當我嘗試使用它,就在table.Cast錯誤;智能感知不會將「Cast」顯示爲有效的方法。

+2

C#2不支持LINQ,所以你不能做到這一點。 – SLaks

+1

你有'使用System.Linq'嗎? – Sebastian

+0

謝謝你塞巴斯蒂安;這是我的問題;我錯過了「使用..」這一行。我現在有的代碼行很好。我也試過「Dictionary dict = HashtableToDictionary (htOffice);」我的散列表使用一個字符串作爲鍵和一個int作爲值。不知道如何將你的回答標記爲答案。 – NoBullMan

回答

2

Enumerable.Cast位於System.Linq命名空間中。不幸的是,LINQ不是.NET 2的一部分。你必須升級到至少3.5版本。

7

Enumerable.Cast在.NET 2中不存在,大多數LINQ相關方法(例如ToDictionary)也不存在。

你需要通過循環手動執行此操作:

public static Dictionary<K,V> HashtableToDictionary<K,V> (Hashtable table) 
{ 
    Dictionary<K,V> dict = new Dictionary<K,V>(); 
    foreach(DictionaryEntry kvp in table) 
     dict.Add((K)kvp.Key, (V)kvp.Value); 
    return dict; 
} 
+2

一個很酷的筆記是你**可以**在2.0中使用擴展方法,如果你使用支持它的編譯器(VS 2008及以上版本)。 [只需要聲明編譯器在創建擴展方法時透明添加的屬性標誌。](http://stackoverflow.com/questions/11346554/can-i-use-extension-methods-and-linq-in-淨2-0 - 或3-0) –