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
{
class Program
{
static void Main(string[] args)
{
NameValueCollection tags = new NameValueCollection();
for (int i = 1; i <= 10; i++)
{
tags.Add(string.Format("tag{0}",i.ToString()),string.Format("The value of tag{0}",i.ToString()));
}
Console.WriteLine(tags["tag2"]);
Console.ReadLine();
}
}
}
Developing software since 1995, starting out with Borland Turbo C++ 3 & Motorolla Assembly.
Eventually learning several different languages such as
Pascal/Delphi,Basic, Visual Basic,FoxPro, ASP, PHP, and Perl.
Currently using the .net framework for most development task.
Hobbies include underwater robotics, and electronics.
George's current language of choice is C#.