Cerebrus

foreach vs. IEnumerator

Aug 2nd, 2010
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.09 KB | None | 0 0
  1. //Related to Question at:
  2. //http://groups.google.com/group/dotnetdevelopment/browse_thread/thread/d76ad9d3f6a811fb
  3.  
  4.    // Uses the foreach statement which hides the complexity of the enumerator.
  5.    // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
  6.    public static void PrintKeysAndValues1( ShortStringDictionary myCol )  {
  7.       foreach ( DictionaryEntry myDE in myCol )
  8.          Console.WriteLine( "   {0,-5} : {1}", myDE.Key, myDE.Value );
  9.       Console.WriteLine();
  10.    }
  11.  
  12.    // Uses the enumerator.
  13.    // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
  14.    public static void PrintKeysAndValues2( ShortStringDictionary myCol )  {
  15.       DictionaryEntry myDE;
  16.       System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator();
  17.       while ( myEnumerator.MoveNext() )
  18.          if ( myEnumerator.Current != null )  {
  19.             myDE = (DictionaryEntry) myEnumerator.Current;
  20.             Console.WriteLine( "   {0,-5} : {1}", myDE.Key, myDE.Value );
  21.          }
  22.       Console.WriteLine();
  23.    }
Advertisement
Add Comment
Please, Sign In to add comment