C# | Get an enumerator that iterates through the stringDictionary
Last Updated :
01 Feb, 2019
StringDictionary.GetEnumerator method is used to return an enumerator that iterates through the string dictionary.
Syntax:
public virtual System.Collections.IEnumerator GetEnumerator ();
Return Value: An IEnumerator that iterates through the string dictionary.
Below given are some examples to understand the implementation in a better way:
Example 1:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringDictionary myDict = new StringDictionary();
myDict.Add( "A" , "Apple" );
myDict.Add( "B" , "Banana" );
myDict.Add( "C" , "Cat" );
myDict.Add( "D" , "Dog" );
IEnumerator myEnumerator = myDict.GetEnumerator();
DictionaryEntry de;
while (myEnumerator.MoveNext()) {
de = (DictionaryEntry)myEnumerator.Current;
Console.WriteLine(de.Key + " " + de.Value);
}
}
}
|
Output:
d Dog
b Banana
c Cat
a Apple
Example 2:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringDictionary myDict = new StringDictionary();
myDict.Add( "I" , "one" );
myDict.Add( "II" , "two" );
myDict.Add( "III" , "three" );
myDict.Add( "IV" , "four" );
myDict.Add( "V" , "five" );
IEnumerator myEnumerator = myDict.GetEnumerator();
DictionaryEntry de;
while (myEnumerator.MoveNext()) {
de = (DictionaryEntry)myEnumerator.Current;
Console.WriteLine(de.Key + " " + de.Value);
}
}
}
|
Output:
iv four
i one
iii three
v five
ii two
Note:
- Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.
- An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.
- This method is an O(1) operation.
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...