Hashtable to Dictionary

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"显示为有效方法.

Ree*_*sey 8

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)

  • 一个很酷的注意事项是,如果您使用支持它的编译器(VS 2008及更高版本),您可以**使用2.0中的扩展方法.[您只需要声明编译器在创建扩展方法时透明地添加的属性标志.](http://stackoverflow.com/questions/11346554/can-i-use-extension-methods-and-linq-in-净2-0 - 或3-0) (2认同)