NoB*_*Man 2 .net c# dictionary hashtable c#-2.0
我试图将哈希表转换为disctionary,并在此处找到一个问题: 在C#中将HashTable转换为Dictionary
public static Dictionary<K,V> HashtableToDictionary<K,V> (Hashtable table)
{
return table
.Cast<DictionaryEntry> ()
.ToDictionary (kvp => (K)kvp.Key, kvp => (V)kvp.Value);
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用它时,表中有一个错误.intellisense不会将"Cast"显示为有效方法.
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;
}
Run Code Online (Sandbox Code Playgroud)