Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lấy enumerator duyệt qua Dictionary trong C#

Giới thiệu

Phương thức GetEnumerator() của Dictionary<TKey, TValue> trả về một IDictionaryEnumerator (hoặc IEnumerator<KeyValuePair<TKey, TValue>>) cho phép duyệt qua các cặp khóa/giá trị. Cách hiện đại hơn là dùng foreach trực tiếp trên dictionary.

Ví dụ 1 - Sử dụng IDictionaryEnumerator

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

public class Demo
{
    public static void Main()
    {
        Dictionary dict = new Dictionary();
        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 duyệt các cặp khóa-giá trị...");
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }
    }
}

Kết quả

Enumerator duyệt các cặp khóa-giá trị...
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

Ví dụ 2 - Dictionary với khóa chuỗi

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

public class Demo
{
    public static void Main()
    {
        Dictionary dict = new Dictionary();
        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 duyệt các cặp khóa-giá trị...");
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }
    }
}

Kết quả

Enumerator duyệt các cặp khóa-giá trị...
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

Cách hiện đại (khuyến nghị)

// Dùng foreach trực tiếp (tự động dùng GetEnumerator)
foreach (var kvp in dict)
{
    Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");
}

// Hoặc chỉ duyệt khóa
foreach (var key in dict.Keys) { ... }

// Hoặc chỉ duyệt giá trị
foreach (var value in dict.Values) { ... }

Lưu ý quan trọng

  • GetEnumerator() trả về IEnumerator<KeyValuePair<TKey, TValue>> (generic) hoặc IDictionaryEnumerator (non-generic).
  • Không nên sửa đổi dictionary (Add/Remove) trong khi đang enumerating → ném InvalidOperationException.
  • Thứ tự duyệt Dictionary không được đảm bảo (tùy implementation). Dùng SortedDictionary hoặc SortedList nếu cần thứ tự.
  • foreach tự động gọi GetEnumerator() và Dispose().