NameValueCollection vs Dictionary<string,string> [duplicate]

ⅰ亾dé卋堺 提交于 2019-11-27 09:23:17

问题


Possible Duplicate:
IDictionary<string, string> or NameValueCollection

Any reason I should use Dictionary<string,string> instead of NameValueCollection?

(in C# / .NET Framework)

Option 1, using 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
}

Option 2, using 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
}

For these use cases, is there any advantage to use one versus the other? Any difference in performance, memory use, sort order, etc.?


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/3001108/namevaluecollection-vs-dictionarystring-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!