How to use NameValueCollection class in C#?

The NameValueCollection class in C# is a specialized collection that allows storing multiple values for a single key. It belongs to the System.Collections.Specialized namespace and is particularly useful for handling web form data, query strings, and HTTP headers where duplicate keys might exist.

Unlike regular dictionaries that allow only one value per key, NameValueCollection can associate multiple string values with a single string key, making it ideal for scenarios like handling multiple form inputs with the same name.

Syntax

Following is the basic syntax for creating and using a NameValueCollection −

NameValueCollection collection = new NameValueCollection();
collection.Add("key", "value");
collection["key"] = "value";  // overwrites existing values
string value = collection["key"];
string[] values = collection.GetValues("key");

Creating and Adding Values

Example

using System;
using System.Collections.Specialized;

class Program {
   static NameValueCollection GetCollection() {
      NameValueCollection myCollection = new NameValueCollection();
      myCollection.Add("Tim", "One");
      myCollection.Add("John", "Two");
      myCollection.Add("Jamie", "Three");
      myCollection.Add("Tim", "Four"); // Multiple values for same key
      return myCollection;
   }

   public static void Main() {
      NameValueCollection myCollection = GetCollection();
      
      // Display all keys
      Console.WriteLine("All Keys:");
      foreach (string key in myCollection.AllKeys) {
         Console.WriteLine(key);
      }
      
      // Display all key-value pairs
      Console.WriteLine("\nAll Key-Value Pairs:");
      foreach (string key in myCollection.AllKeys) {
         Console.WriteLine(key + ": " + myCollection[key]);
      }
   }
}

The output of the above code is −

All Keys:
Tim
John
Jamie

All Key-Value Pairs:
Tim: One,Four
John: Two
Jamie: Three

Working with Multiple Values

Example

using System;
using System.Collections.Specialized;

class Program {
   public static void Main() {
      NameValueCollection colors = new NameValueCollection();
      colors.Add("primary", "red");
      colors.Add("primary", "blue");
      colors.Add("primary", "yellow");
      colors.Add("secondary", "green");
      colors.Add("secondary", "orange");
      
      // Get all values for a key
      string[] primaryColors = colors.GetValues("primary");
      Console.WriteLine("Primary colors:");
      foreach (string color in primaryColors) {
         Console.WriteLine("- " + color);
      }
      
      // Get comma-separated values
      Console.WriteLine("\nPrimary colors (comma-separated): " + colors["primary"]);
      
      // Check if key exists
      Console.WriteLine("\nContains 'secondary' key: " + (colors["secondary"] != null));
      Console.WriteLine("Count of items: " + colors.Count);
   }
}

The output of the above code is −

Primary colors:
- red
- blue
- yellow

Primary colors (comma-separated): red,blue,yellow

Contains 'secondary' key: True
Count of items: 2

Common Methods and Properties

Method/Property Description
Add(key, value) Adds a new value to the specified key
Remove(key) Removes all values associated with the key
GetValues(key) Returns string array of all values for the key
AllKeys Gets all keys in the collection
Count Gets the number of key-value pairs
Clear() Removes all key-value pairs

Modifying and Removing Values

Example

using System;
using System.Collections.Specialized;

class Program {
   public static void Main() {
      NameValueCollection config = new NameValueCollection();
      config.Add("timeout", "30");
      config.Add("retries", "3");
      config.Add("timeout", "60"); // Additional value
      
      Console.WriteLine("Before modification:");
      Console.WriteLine("Timeout: " + config["timeout"]);
      Console.WriteLine("Count: " + config.Count);
      
      // Set overwrites all existing values for the key
      config.Set("timeout", "45");
      
      Console.WriteLine("\nAfter Set operation:");
      Console.WriteLine("Timeout: " + config["timeout"]);
      
      // Remove a key entirely
      config.Remove("retries");
      
      Console.WriteLine("\nAfter removing 'retries':");
      Console.WriteLine("Count: " + config.Count);
      foreach (string key in config.AllKeys) {
         Console.WriteLine(key + ": " + config[key]);
      }
   }
}

The output of the above code is −

Before modification:
Timeout: 30,60
Count: 2

After Set operation:
Timeout: 45

After removing 'retries':
Count: 1
timeout: 45

Common Use Cases

  • Web form processing − handling multiple checkboxes or select options with the same name.

  • HTTP headers − managing headers where the same header name can appear multiple times.

  • Configuration settings − storing multiple values for configuration keys.

  • Query string parameters − handling URL parameters that may have duplicate names.

Conclusion

NameValueCollection is a specialized collection class that excels at managing key-value pairs where keys can have multiple values. It provides convenient methods for adding, retrieving, and manipulating string-based data, making it particularly useful in web development scenarios and configuration management.

Updated on: 2026-03-17T07:04:35+05:30

752 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements