Mega Code Archive

 
Categories / C# / Collections Data Structure
 

StringCollection represents a collection of strings

using System; using System.Collections; using System.Collections.Specialized; public class SamplesStringCollection  {    public static void Main()  {       StringCollection myCol = new StringCollection();              String[] myArr = new String[] { "a", "b", "a" };              myCol.AddRange( myArr );              PrintValues1( myCol );              PrintValues2( myCol );              PrintValues3( myCol );              myCol.Add( "a" );       myCol.Insert( 3, "a" );              PrintValues1( myCol );              myCol.Remove( "b" );       PrintValues1( myCol );              int i = myCol.IndexOf( "a" );       while ( i > -1 )  {          myCol.RemoveAt( i );          i = myCol.IndexOf( "a" );       }              if ( myCol.Contains( "a" ) )          Console.WriteLine( "The collection still contains a." );              PrintValues1( myCol );              String[] myArr2 = new String[myCol.Count];       myCol.CopyTo( myArr2, 0 );       for ( i = 0; i < myArr2.Length; i++ )  {          Console.WriteLine( "   [{0}] {1}", i, myArr2[i] );       }              myCol.Clear();       PrintValues1( myCol );    }    public static void PrintValues1( StringCollection myCol )  {       foreach ( Object obj in myCol )          Console.WriteLine( "   {0}", obj );    }    public static void PrintValues2( StringCollection myCol )  {       StringEnumerator myEnumerator = myCol.GetEnumerator();       while ( myEnumerator.MoveNext() )          Console.WriteLine( "   {0}", myEnumerator.Current );    }    public static void PrintValues3( StringCollection myCol )  {       for ( int i = 0; i < myCol.Count; i++ )          Console.WriteLine( "   {0}", myCol[i] );    } }