Mega Code Archive

 
Categories / C# / Collections Data Structure
 

Represents a collection of associated String keys and String values

using System; using System.Collections; using System.Collections.Specialized; public class SamplesNameValueCollection  {    public static void Main()  {       NameValueCollection myCol = new NameValueCollection();       myCol.Add( "A", "a" );       myCol.Add( "B", "b" );       myCol.Add( "C", "c" );       PrintKeysAndValues( myCol );       PrintKeysAndValues2( myCol );       Console.WriteLine( "Index 1 contains the value {0}.", myCol[1] );       Console.WriteLine( "Key \"A\" has the value {0}.", myCol["A"] );       String[] myStrArr = new String[myCol.Count];       myCol.CopyTo( myStrArr, 0 );       foreach ( String s in myStrArr )          Console.WriteLine( "   {0}", s );       myCol.Remove( "A" );       PrintKeysAndValues( myCol );       myCol.Clear();       PrintKeysAndValues( myCol );    }    public static void PrintKeysAndValues( NameValueCollection myCol )  {       foreach ( String s in myCol.AllKeys )          Console.WriteLine( "   {0,-10} {1}", s, myCol[s] );    }    public static void PrintKeysAndValues2( NameValueCollection myCol )  {       for ( int i = 0; i < myCol.Count; i++ )          Console.WriteLine( "   [{0}]     {1,-10} {2}", i, myCol.GetKey(i), myCol.Get(i) );    } }