在C#中将HashTable转换为Dictionary

RKP*_*RKP 35 .net c# generics dictionary hashtable

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

age*_*t-j 61

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)


Kir*_*huk 9

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);
Run Code Online (Sandbox Code Playgroud)

  • 感谢不需要循环的解决方案,这正是我所寻求的.但是我接受了另一个解决方案作为答案,因为它也进行了强制类型的转换,并且为它定义了扩展方法.上面的一个返回键和值的通用对象类型,这比hashtable没有任何额外的优势. (3认同)

Rob*_*rto 8

Agent-j 答案的扩展方法版本:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)