Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 813
RKP Avatar asked Jun 23 '11 14:06

RKP


4 Answers

public static Dictionary<K,V> HashtableToDictionary<K,V> (Hashtable table)
{
   return table
     .Cast<DictionaryEntry> ()
     .ToDictionary (kvp => (K)kvp.Key, kvp => (V)kvp.Value);
}
like image 173
agent-j Avatar answered Nov 04 '22 17:11

agent-j


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);
like image 30
Kirill Polishchuk Avatar answered Nov 04 '22 18:11

Kirill Polishchuk


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);
    }
}
like image 6
Roberto Avatar answered Nov 04 '22 18:11

Roberto


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]);
}
like image 4
alx Avatar answered Nov 04 '22 17:11

alx