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

รับตัวแปรระบุ (enumerator) สำหรับวนลูป Dictionary ใน C#

บทความนี้สาธิตวิธีรับ IDictionaryEnumerator เพื่อวนลูปผ่าน Dictionary<TKey, TValue> ใน C#

ตัวอย่างที่ 1: Dictionary<int, string> กับ IDictionaryEnumerator

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Dictionary<int, string> dict = new Dictionary<int, string>();
        dict.Add(100, "Laptop");
        dict.Add(150, "Desktop");
        dict.Add(200, "Earphone");
        dict.Add(300, "Tablet");
        dict.Add(500, "Speakers");
        dict.Add(750, "HardDisk");
        dict.Add(1000, "SSD");

        IDictionaryEnumerator demoEnum = dict.GetEnumerator();

        Console.WriteLine("Enumerator iterating key-value pairs...");
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }
    }
}

ผลลัพธ์

Enumerator iterating key-value pairs...
Key = 100, Value = Laptop
Key = 150, Value = Desktop
Key = 200, Value = Earphone
Key = 300, Value = Tablet
Key = 500, Value = Speakers
Key = 750, Value = HardDisk
Key = 1000, Value = SSD

ตัวอย่างที่ 2: Dictionary<string, string> กับ IDictionaryEnumerator

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Dictionary<string, string> dict = new Dictionary<string, string>();
        dict.Add("One", "Laptop");
        dict.Add("Two", "Desktop");
        dict.Add("Three", "Earphone");
        dict.Add("Four", "Tablet");
        dict.Add("Five", "Speakers");
        dict.Add("Six", "HardDisk");
        dict.Add("Seven", "SSD");
        dict.Add("Eight", "Keyboard");
        dict.Add("Nine", "Mouse");

        IDictionaryEnumerator demoEnum = dict.GetEnumerator();

        Console.WriteLine("Enumerator iterating key-value pairs...");
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }
    }
}

ผลลัพธ์

Enumerator iterating key-value pairs...
Key = One, Value = Laptop
Key = Two, Value = Desktop
Key = Three, Value = Earphone
Key = Four, Value = Tablet
Key = Five, Value = Speakers
Key = Six, Value = HardDisk
Key = Seven, Value = SSD
Key = Eight, Value = Keyboard
Key = Nine, Value = Mouse

สรุปและแนวทางปฏิบัติที่ดีกว่า

  • GetEnumerator() คืนค่า IDictionaryEnumerator (implements IEnumerator) — รูปแบบเก่า (non-generic)
  • แนะนำให้ใช้ foreach แทน — สะดวกกว่า อ่านง่ายกว่า และ type-safe:
    foreach (var kvp in dict)
    {
        Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");
    }
  • หากต้องการ enumerator แบบ generic ให้ใช้ dict.GetEnumerator() ซึ่งคืนค่า Dictionary<TKey, TValue>.Enumerator (struct) — ใช้กับ while (enumerator.MoveNext()) ได้เช่นกัน
  • IDictionaryEnumerator มีคุณสมบัติ Key, Value, Entry (DictionaryEntry)
  • Dictionary ไม่รับประกันลำดับ — หากต้องการลำดับ ใช้ SortedDictionary<TKey, TValue> หรือ SortedList<TKey, TValue>

การใช้งาน Enumerator แบบ Generic (แนะนำ)

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        var dict = new Dictionary<int, string> { { 1, "One" }, { 2, "Two" } };

        // แบบ foreach (แนะนำ)
        foreach (var kvp in dict)
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");

        // แบบ Enumerator struct (generic) - เมื่อต้องควบคุมการวนลูปเอง
        var enumerator = dict.GetEnumerator();
        while (enumerator.MoveNext())
        {
            var kvp = enumerator.Current;
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
        enumerator.Dispose(); // struct ไม่ต้อง dispose ก็ได้ แต่ทำได้
    }
}