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?
How to convert NameValueCollection to Hashtable
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]);
}
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
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.
© 2022 - 2024 — McMap. All rights reserved.
Hashtable
so using aDictionary
is not an option... – Cirone