Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Dictionary<> to Hashtable in C#?

Tags:

c#

.net

I see many question/answers about how to convert a Hashtable to a Dictionary, but how can I convert a Dictionary to a Hashtable?

like image 242
jpints14 Avatar asked Mar 29 '12 14:03

jpints14


People also ask

What is faster in C#: Dictionary or Hashtable?

Dictionary is faster than hashtable as dictionary is a generic strong type. Hashtable is slower as it takes object as data type which leads to boxing and unboxing.

Is Dictionary A Hashtable C#?

Dictionary is NOT implemented as a HashTable, but it is implemented following the concept of a hash table. The implementation is unrelated to the HashTable class because of the use of Generics, although internally Microsoft could have used the same code and replaced the symbols of type Object with TKey and TValue. In .

Is Dictionary Hashtable?

Hashtable and Dictionary are collection of data structures to hold data as key-value pairs. Dictionary is generic type, hash table is not a generic type. The Hashtable is a weakly typed data structure, so you can add keys and values of any Object Type to the Hashtable.

Which one is better Hashtable or Dictionary?

Dictionary is a generic type and returns an error if you try to find a key which is not there. The Dictionary collection is faster than Hashtable because there is no boxing and unboxing.


2 Answers

The easiest way is using constructor of Hashtable:

        var dictionary = new Dictionary<object, object>();
        //... fill the dictionary
        var hashtable = new Hashtable(dictionary);
like image 172
asktomsk Avatar answered Sep 17 '22 17:09

asktomsk


Dictionary<int, string> dictionary = new Dictionary<int, string>
   {
      {1,"One"},
      {2,"Two"}
   };
Hashtable hashtable = new Hashtable(dictionary);

Try this

like image 31
Nazar Tereshkovych Avatar answered Sep 18 '22 17:09

Nazar Tereshkovych