Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameValueCollection vs Dictionary<string,string> [duplicate]

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.?

like image 369
frankadelic Avatar asked Jun 08 '10 20:06

frankadelic


People also ask

When to use NameValueCollection?

NameValueCollection is used to store a collection of associated String keys and String values that can be accessed either with the key or with the index. It is very similar to C# HashTable, HashTable also stores data in Key , value format . NameValueCollection can hold multiple string values under a single key.

Does C# dictionary allow duplicate keys?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

Is NameValueCollection case sensitive?

The name is case-insensitive.


1 Answers

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.

like image 50
Keltex Avatar answered Oct 22 '22 08:10

Keltex