The NameValueCollection quick example





3.00/5 (1 vote)
A quick example on how to use the NameValueCollection class
Introduction
One of the most common questions I've been asked is "How can I make a collection that allows me to enter either a key or an index to pull a value?" (well, usually it's formed more like "I want to build a property in my class that works just like the .Items property in x class", "How can I make a collection that works like AppSettings["key"], or some other specific but related question)
I've been asked this question often enough that I'm just going to put together a quick tip / example so people can reference it whenever they need to.
Background
You'll need to reference the System.Collections.Specialized
namespace and use the NameValueCollection
class
Using the code
Below is a quick console application that creates a NameValueCollection
variable, Populates it with data, and then displays one of the values to the console. Very simple example code that you can reference and expand upon in your own projects.
using System;
using System.Collections.Specialized;
namespace ConsoleApplication1
{
/// <summary>
/// An incredibly simple demonstration of
/// NameValueCollection
/// </summary>
class Program
{
static void Main(string[] args)
{
// Say we want a simple string collection. Similar to AppSettings or the like.
// make a collection
NameValueCollection tags = new NameValueCollection();
// quick loop to populate it with some demo values.
for (int i = 1; i <= 10; i++)
{
tags.Add(string.Format("tag{0}",i.ToString()),string.Format("The value of tag{0}",i.ToString()));
}
// in this case we know there is an index of tag2 so we'll hard
// code for the demo
Console.WriteLine(tags["tag2"]);
Console.ReadLine();
}
}
}