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)
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)
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)