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.