StringCollection represents a collection of strings. : StringCollection « Collections Data Structure « C# / C Sharp






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] );
   }
}

   
  








Related examples in the same category

1.Adds a string to the end of the StringCollection.
2.Removes all the strings from the StringCollection.
3.Determines whether the specified string is in the StringCollection.
4.Copies the entire StringCollection values to a one-dimensional array of strings
5.StringEnumerator supports a simple iteration over a StringCollection.