Use an enumerator to loop through an ArrayList in CSharp

Description

The following code shows how to use an enumerator to loop through an ArrayList.

Example


using System; /* w  w w  .  j  a va 2 s. com*/
using System.Collections; 
 
public class EnumeratorDemo {  
  public static void Main() { 
    ArrayList list = new ArrayList(1); 
 
    for(int i=0; i < 10; i++) 
      list.Add(i); 
 
    // Use enumerator to access list. 
    IEnumerator etr = list.GetEnumerator(); 
    while(etr.MoveNext())  
      Console.Write(etr.Current + " "); 
 
    Console.WriteLine(); 
 
    // Re-enumerate the list. 
    etr.Reset(); 
    while(etr.MoveNext())  
      Console.Write(etr.Current + " "); 
 
    Console.WriteLine(); 
  } 
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Collections »




ArrayList
BitArray
Collection
Comparer
HashSet
Hashtable
LinkedList
List
ListDictionary
OrderedDictionary
Queue
SortedList
SortedSet
Stack
StringCollection
StringDictionary