Search code examples
c#.netgenericsdictionaryhashtable

Convert HashTable to Dictionary in C#


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?


Solution

  • public static Dictionary<K,V> HashtableToDictionary<K,V> (Hashtable table)
    {
       return table
         .Cast<DictionaryEntry> ()
         .ToDictionary (kvp => (K)kvp.Key, kvp => (V)kvp.Value);
    }