How to convert NameValueCollection to Hashtable

2020-08-12 18:32发布

问题:

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?

回答1:

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]);
}


回答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.



标签: c# .net .net-3.5