獲取遍歷 C# 中的集合的列舉器


要獲取遍歷集合的列舉器,程式碼如下 −

示例

 線上演示

using System;
using System.Collections.ObjectModel;
public class Demo {
   public static void Main(){
      Collection<string> col = new Collection<string>();
      col.Add("Andy");
      col.Add("Kevin");
      col.Add("John");
      col.Add("Kevin");
      col.Add("Mary");
      col.Add("Katie");
      col.Add("Barry");
      col.Add("Nathan");
      col.Add("Mark");
      Console.WriteLine("Count of elements = "+ col.Count);
      Console.WriteLine("Iterating through the collection...");
      var enumerator = col.GetEnumerator();
      while (enumerator.MoveNext()) {
         Console.WriteLine(enumerator.Current);
      }
   }
}

輸出

這會產生以下輸出 −

Count of elements = 9
Iterating through the collection...
Andy
Kevin
John
Kevin
Mary
Katie
Barry
Nathan
Mark

示例

讓我們再看一個例子 −

 線上演示

using System;
using System.Collections.ObjectModel;
public class Demo {
   public static void Main(){
      Collection<int> col = new Collection<int>();
      col.Add(100);
      col.Add(200);
      col.Add(300);
      col.Add(400);
      col.Add(500);
      Console.WriteLine("Count of elements = "+ col.Count);
      Console.WriteLine("Iterating through the collection...");
      var enumerator = col.GetEnumerator();
      while (enumerator.MoveNext()) {
         Console.WriteLine(enumerator.Current);
      }
   }
}

輸出

這會產生以下輸出 −

Count of elements = 5
Iterating through the collection...
100
200
300
400
500

更新於: 06-05-2020

72 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.