📜  C#|获取一个遍历字典的枚举数

📅  最后修改于: 2021-05-30 01:00:43             🧑  作者: Mango

Dictionary .GetEnumerator方法用于返回迭代通过Dictionary 的枚举数。

句法:

返回值:此方法返回Dictionary .Dictionary 的枚举器结构。

下面的程序说明了Dictionary .GetEnumerator方法的用法:

范例1:

// C# code to get an IDictionaryEnumerator
// that iterates through the Dictionary
using System;
using System.Collections;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Dictionary named myDict
        Dictionary myDict =
           new Dictionary();
  
        myDict.Add("Australia", "Canberra");
        myDict.Add("Belgium", "Brussels");
        myDict.Add("Netherlands", "Amsterdam");
        myDict.Add("China", "Beijing");
        myDict.Add("Russia", "Moscow");
        myDict.Add("India", "New Delhi");
  
        // To get an IDictionaryEnumerator
        // for the Dictionary
        IDictionaryEnumerator myEnumerator = 
                     myDict.GetEnumerator();
  
        // If MoveNext passes the end of the
        // collection, the enumerator is positioned
        // after the last element in the collection
        // and MoveNext returns false.
        while (myEnumerator.MoveNext())
            Console.WriteLine(myEnumerator.Key + " --> "
                              + myEnumerator.Value);
    }
}
输出:
Australia --> Canberra
Belgium --> Brussels
Netherlands --> Amsterdam
China --> Beijing
Russia --> Moscow
India --> New Delhi

范例2:

// C# code to get an IDictionaryEnumerator
// that iterates through the Dictionary
using System;
using System.Collections;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Dictionary named myDict
        Dictionary myDict = 
           new Dictionary();
  
        // Adding key/value pairs in myDict
        myDict.Add("I", "C");
        myDict.Add("II", "C++");
        myDict.Add("III", "Java");
        myDict.Add("IV", "Python");
        myDict.Add("V", "C#");
  
        // To get an IDictionaryEnumerator
        // for the Dictionary
        IDictionaryEnumerator myEnumerator = 
                     myDict.GetEnumerator();
  
        // If MoveNext passes the end of the
        // collection, the enumerator is positioned
        // after the last element in the collection
        // and MoveNext returns false.
        while (myEnumerator.MoveNext())
            Console.WriteLine(myEnumerator.Key + " --> "
                              + myEnumerator.Value);
    }
}
输出:
I --> C
II --> C++
III --> Java
IV --> Python
V --> C#

笔记:

  • C#语言的foreach语句隐藏了枚举器的复杂性。因此,建议使用foreach,而不是直接操作枚举器。
  • 枚举数可用于读取集合中的数据,但不能用于修改基础集合。
  • 在调用MoveNextReset之前,Current返回相同的对象。 MoveNext将Current设置为下一个元素。
  • 只要集合保持不变,枚举数将保持有效。如果对集合进行了更改(例如添加,修改或删除元素),则枚举数将无法恢复,并且其行为是不确定的。
  • 此方法是O(1)操作。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.dictionary-2.getenumerator?view=netframework-4.7.2