How do I convert a HashTable to Dictionary in C#? Is it possible?
For example, if I have a collection of objects in a HashTable and I want to convert it to a dictionary of objects with a specific type, how can I do that?
public static Dictionary<K,V> HashtableToDictionary<K,V> (Hashtable table)
{
return table
.Cast<DictionaryEntry> ()
.ToDictionary (kvp => (K)kvp.Key, kvp => (V)kvp.Value);
}
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);
Extension method version of agent-j's answer:
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);
}
}
You can create an extension method for that
Dictionary<KeyType, ItemType> d = new Dictionary<KeyType, ItemType>();
foreach (var key in hashtable.Keys)
{
d.Add((KeyType)key, (ItemType)hashtable[key]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With