如何NameValueCollection中转换为哈希表转换为、NameValueCollection、哈希表

2023-09-03 15:52:41 作者:爱过人渣怪我眼瞎

我有一个的NameValueCollection 对象,我需要将其转换为一个的Hashtable 对象,preferrably在一行code。我怎样才能做到这一点?

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?

推荐答案

您应该考虑使用一个通用的 词典 ,而不是因为它的强类型,而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]);

编辑:基于您的评论,得到一个哈希表,你仍然可以使用上面的方法,并添加更多的线。你总是可以使这项工作在同一行,但2线更具可读性。

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

另外,使用循环将是pre-.NET 3.5做法:

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