How to convert NameValueCollection to Hashtable
Asked Answered
C

2

12

I have a NameValueCollection object and I need to convert it to a Hashtable object, preferrably in one line of code. How can I achieve this?

Cirone answered 8/4, 2011 at 20:38 Comment(0)
N
20

You should consider using a generic Dictionary instead since it's strongly-typed, whereas a Hashtable isn't. Try this:

NameValueCollection col = new NameValueCollection();
col.Add("red", "rouge");
col.Add("green", "verde");
col.Add("blue", "azul");

var dict = col.AllKeys
              .ToDictionary(k => k, k => col[k]);

EDIT: Based on your comment, to get a HashTable you could still use the above approach and add one more line. You could always make this work in one line but 2 lines are more readable.

Hashtable hashTable = new Hashtable(dict);

Alternately, the pre-.NET 3.5 approach using a loop would be:

Hashtable hashTable = new Hashtable();
foreach (string key in col)
{
    hashTable.Add(key, col[key]);
}
Notepaper answered 8/4, 2011 at 20:43 Comment(3)
the problem is that I'm using an API that expects a Hashtable so using a Dictionary is not an option...Cirone
there is a catch here. NameValueCollection allows duplicate keys. In that case, all values are inserted for the same key in HashTable. there is only one entry per unique key. e.g. if you have "red" key listed twice against "rouge" and "verde" values, both values will be listed against hash key "red" as a single key.Dowd
@Dowd good point! Some post processing would need to be done to apply any special handling depending on the OP's needs.Notepaper
K
2

It takes more than one line but it's decently simple

NameValueCollection nv = new NameValueCollection();
Hashtable hashTable = new Hashtable();

nv.Add("test", "test");

foreach (string key in nv.Keys)
{
    hashTable.Add(key, nv[key]);
}

It compiles and executes as expected.

Kayser answered 8/4, 2011 at 21:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.