OrderedDictionary.GetEnumerator方法返回一个IDictionaryEnumerator对象,该对象遍历OrderedDictionary集合。
句法:
public virtual System.Collections.IDictionaryEnumerator GetEnumerator ();
返回值: OrderedDictionary集合的IDictionaryEnumerator对象。
下面给出了一些示例,以更好地理解实现:
范例1:
// C# code to get an IDictionaryEnumerator
// object that iterates through the
// OrderedDictionary collection.
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
// Driver method
public static void Main()
{
// Creating a orderedDictionary named myDict
OrderedDictionary myDict = new OrderedDictionary();
// Adding key and value in myDict
myDict.Add("key1", "value1");
myDict.Add("key2", "value2");
myDict.Add("key3", "value3");
myDict.Add("key4", "value4");
myDict.Add("key5", "value5");
// To Get an IDictionaryEnumerator object
// that iterates through the OrderedDictionary
// collection.
IDictionaryEnumerator myEnumerator = myDict.GetEnumerator();
while (myEnumerator.MoveNext()) {
Console.WriteLine(myEnumerator.Key + " --> "
+ myEnumerator.Value);
}
}
}
输出:
key1 --> value1
key2 --> value2
key3 --> value3
key4 --> value4
key5 --> value5
范例2:
// C# code to get an IDictionaryEnumerator
// object that iterates through the
// OrderedDictionary collection.
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
// Driver method
public static void Main()
{
// Creating a orderedDictionary named myDict
OrderedDictionary myDict = new OrderedDictionary();
// Adding key and value in myDict
myDict.Add("A", "Apple");
myDict.Add("B", "Banana");
myDict.Add("C", "Cat");
myDict.Add("D", "Dog");
// To Get an IDictionaryEnumerator object
// that iterates through the OrderedDictionary
// collection.
IDictionaryEnumerator myEnumerator = myDict.GetEnumerator();
while (myEnumerator.MoveNext()) {
Console.WriteLine(myEnumerator.Key + " --> "
+ myEnumerator.Value);
}
}
}
输出:
A --> Apple
B --> Banana
C --> Cat
D --> Dog
笔记:
- 枚举数可用于读取集合中的数据,但不能用于修改基础集合。
- 最初,枚举数位于集合中第一个元素之前。
- 此方法是O(1)操作。
- 只要集合保持不变,枚举数将保持有效。如果对集合进行了更改(例如添加,修改或删除元素),则枚举数将无法恢复,并且其行为是不确定的。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.ordereddictionary.getenumerator?view=netframework-4.7.2