jpints14
jpints14

Reputation: 1371

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

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

Upvotes: 12

Views: 15152

Answers (4)

asktomsk
asktomsk

Reputation: 2298

The easiest way is using constructor of Hashtable:

        var dictionary = new Dictionary<object, object>();
        //... fill the dictionary
        var hashtable = new Hashtable(dictionary);

Upvotes: 31

to StackOverflow
to StackOverflow

Reputation: 124696

You might want to consider using the Hashtable constructor overload that takes an IEqualityComparer parameter:

var hashtable = new Hashtable(dictionary, (IEqualityComparer) dictionary.Comparer); 

In this way, your Hashtable uses the same Comparer as the dictionary. For example, if your dictionary used a case-insensitive string key, you might want your Hashtable to be case-insensitive too. E.g.:

var d = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
d.Add("a", "a");
d.Add("b", "b");

bool found;
found = d.ContainsKey("A"); // true

var hashtable1 = new Hashtable(d);
var hashtable2 = new Hashtable(d, (IEqualityComparer) d.Comparer);

found = hashtable1["A"] != null; // false - by default it's case-sensitive

found = hashtable2["A"] != null; // true - uses same comparer as the original dictionary

Upvotes: 4

Nazar Tereshkovych
Nazar Tereshkovych

Reputation: 1472

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

Try this

Upvotes: 8

Marc Gravell
Marc Gravell

Reputation: 1062660

Seems pretty rare to want to do, but at the simplest:

var hash = new Hashtable();
foreach(var pair in dictionary) {
    hash.Add(pair.Key,pair.Value);
}

(assuming no unusual "implements typed equality check but not untyped equality check" etc)

Upvotes: 5

Related Questions