Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การใช้ Enumerator วนลูป List ใน C# พร้อมตัวอย่าง


ใน C# สามารถใช้ Enumerator (ผ่าน GetEnumerator()) เพื่อวนลูปผ่านองค์ประกอบของ List แบบควบคุมด้วยตนเอง (manual iteration) แทนที่จะใช้ foreach

ตัวอย่างที่ 1: ใช้ Enumerator กับ List<String>

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main(String[] args)
    {
        List list1 = new List();
        list1.Add("One");
        list1.Add("Two");
        list1.Add("Three");
        list1.Add("Four");
        list1.Add("Five");

        Console.WriteLine("Elements in List1...");
        foreach (string res in list1)
        {
            Console.WriteLine(res);
        }

        List list2 = new List();
        list2.Add("India");
        list2.Add("US");
        list2.Add("UK");
        list2.Add("Canada");
        list2.Add("Poland");
        list2.Add("Netherlands");

        Console.WriteLine("\nElements in List2...");
        List.Enumerator demoEnum = list2.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            string res = demoEnum.Current;
            Console.WriteLine(res);
        }

        Console.WriteLine("\nIs List2 equal to List1? = " + list2.Equals(list1));
    }
}

ผลลัพธ์

Elements in List1...
One
Two
Three
Four
Five

Elements in List2...
India
US
UK
Canada
Poland
Netherlands

Is List2 equal to List1? = False

ตัวอย่างที่ 2: Enumerator กับ List 10 องค์ประกอบ

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main(String[] args)
    {
        List list = new List();
        list.Add("One");
        list.Add("Two");
        list.Add("Three");
        list.Add("Four");
        list.Add("Five");
        list.Add("Six");
        list.Add("Seven");
        list.Add("Eight");
        list.Add("Nine");
        list.Add("Ten");

        Console.WriteLine("Enumerator iterates through the list elements...");
        List.Enumerator demoEnum = list.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            string res = demoEnum.Current;
            Console.WriteLine(res);
        }
    }
}

ผลลัพธ์

Enumerator iterates through the list elements...
One
Two
Three
Four
Five
Six
Seven
Eight
Nine
Ten

ข้อสังเกตสำคัญ

  • GetEnumerator() คืนค่า List<T>.Enumerator (struct) — ไม่ใช่ IEnumerator<T> โดยตรง (แต่ implement interface นั้น)
  • MoveNext() ขยับไปยังองค์ประกอบถัดไป — คืน false เมื่อจบ
  • Current คืนค่าองค์ประกอบปัจจุบัน
  • Enumerator เป็น read-only — ไม่สามารถแก้ไข List ระหว่าง enumerate (จะโยน InvalidOperationException)
  • foreach เป็น syntactic sugar ของ pattern นี้ — ใช้ foreach ตรงไปตรงมาได้ในกรณีส่วนใหญ่
  • ใช้ Enumerator โดยตรงเมื่อต้องการควบคุมการวนลูปละเอียด (เช่น ข้าม, หยุดชั่วคราว, วนซ้อน)