How to use C# NameValueCollection Class

The NameValueCollection class in C# is designed to store a collection of String keys and String values, allowing access to the data either through the keys or by index. It provides functionality similar to the HashTable class, which also stores data in a key-value format.

One key feature of the NameValueCollection is its ability to hold multiple string values under a single key. This enables efficient management of related data that needs to be grouped together. As elements are added to a NameValueCollection, the capacity automatically adjusts to accommodate the data through dynamic reallocation.

Adding new pairs

NameValueCollection.Add(name,value) NameValueCollection pair = new NameValueCollection(); pair.Add("High", "80");

To utilize the NameValueCollection, it is necessary to import the System.Collections.Specialized namespace into your program. This allows access to the specialized classes and functionality provided by NameValueCollection.

Get the value of corresponding Key

string[] NameValueCollection.GetValues(index); NameValueCollection pair = new NameValueCollection(); pair.Add("High", "80"); string[] vals = pair.GetValues(1);

It's important to note that the NameValueCollection provides additional methods and properties for manipulating and querying the collection. These features enable developers to control and customize the behavior of the collection according to their specific requirements.

Full Source C#
using System; using System.Collections; using System.Windows.Forms; using System.Collections.Specialized; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { NameValueCollection markStatus = new NameValueCollection(); string[] values = null; markStatus.Add("Very High", "80"); markStatus.Add("High", "60"); markStatus.Add("medium", "50"); markStatus.Add("Pass", "40"); foreach (string key in markStatus.Keys) { values = markStatus.GetValues(key); foreach (string value in values) { MessageBox.Show (key + " - " + value); } } } } }

Conclusion

The NameValueCollection class in C# offers a powerful tool for organizing and accessing key-value data, providing flexibility, and facilitating efficient data management within applications.