Reputation: 1371
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
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
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
Reputation: 1472
Dictionary<int, string> dictionary = new Dictionary<int, string>
{
{1,"One"},
{2,"Two"}
};
Hashtable hashtable = new Hashtable(dictionary);
Try this
Upvotes: 8
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