Convert HashTable to Dictionary in C#
28,805
Solution 1
public static Dictionary<K,V> HashtableToDictionary<K,V> (Hashtable table)
{
return table
.Cast<DictionaryEntry> ()
.ToDictionary (kvp => (K)kvp.Key, kvp => (V)kvp.Value);
}
Solution 2
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);
Solution 3
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);
}
}
Solution 4
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]);
}
Author by
RKP
Senior Application developer on Microsoft Technology stack
Updated on January 04, 2021Comments
-
RKP over 3 years
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?
-
RKP almost 13 yearsthanks for the solution which doesn't require looping which is what I was looking for. however I accepted the other solution as answer because it does the casting to correct type as well and has an extension method defined for it. the above one returns generic object type for both key and value which gives no additional advantage over hashtable.
-
RKP almost 13 yearsthanks for the complete answer of converting to dictionary and also casting of the key and value to the given type.