NameValueCollection vs Dictionary < string,string >

可能的复制品:
IDictionary < string,string > 或 NameValueCollection

为什么我应该使用 Dictionary < string,string > 而不是 NameValueCollection?

(在 C #/. NET Framework 中)

选项1,使用 NameValueCollection:

//enter values:
NameValueCollection nvc = new NameValueCollection()
{
{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"}
};


// retrieve values:
foreach(string key in nvc.AllKeys)
{
string value = nvc[key];
// do something
}

选项2,使用 Dictionary < string,string > ..。

//enter values:
Dictionary<string, string> dict = new Dictionary<string, string>()
{
{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"}
};


// retrieve values:
foreach (KeyValuePair<string, string> kvp in dict)
{
string key = kvp.Key;
string val = kvp.Value;
// do something
}

对于这些用例,使用其中一种与使用另一种相比有什么优势吗?性能、内存使用、排序顺序等方面的任何差异。?

95006 次浏览

They aren't semantically identical. The NameValueCollection can have duplicate keys while the Dictionary cannot.

Personally if you don't have duplicate keys, then I would stick with the Dictionary. It's more modern, uses IEnumerable<> which makes it easy to mingle with Linq queries. You can even create a Dictionary using the Linq ToDictionary() method.

NameValueCollection is string typed whereas Dictionary leverages generics to allow type variance. See Benefits of Generics.

Dictionary will be much faster. NameValueCollection allows duplicate keys. Which could be bad in certain situations, or desired in other. Dictionary does not allow duplicate keys.

From: http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

The Dictionary<(Of <(TKey, TValue>)>) generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary<(Of <(TKey, TValue>)>) class is implemented as a hash table.