February 3, 2016

Difference between NameValueCollection and Dictionary in C#

The NameValueCollection can have duplicate keys while the Dictionary cannot.
Dictionary will be much faster because duplicate keys not allowed here while NameValueCollection allows duplicate keys.

//Add values into NameValueCollection object
NameValueCollection objNvc = new NameValueCollection()
{
  {
"key1", "value1"},
  {
"key2", "value2"}
};

// Access values from NameValueCollection object
foreach (string key in objNvc.AllKeys)
{
   
string value = objNvc[key];
}

//Add values into Dictionary object

Dictionary<string, string> objDictionary = new Dictionary<string, string>()
{
  {
"key1", "value1"},
  {
"key2", "value2"}
};

// Retrieve values from Dictionary object
foreach (KeyValuePair<string, string> kvp in objDictionary)
{
   
string key = kvp.Key;
   
string
val = kvp.Value;
}

No comments:

Post a Comment