Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert NameValueCollection to Hashtable

Tags:

c#

.net

.net-3.5

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?

like image 695
MarioVW Avatar asked Apr 08 '11 20:04

MarioVW


1 Answers

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]);
}
like image 108
Ahmad Mageed Avatar answered Oct 20 '22 04:10

Ahmad Mageed