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

Lấy IDictionaryEnumerator trong OrderedDictionary C#

Giới thiệu

OrderedDictionary (namespace System.Collections.Specialized) hỗ trợ GetEnumerator() trả về IDictionaryEnumerator để duyệt cặp khóa-giá trị theo thứ tự chèn.

Ví dụ 1: Duyệt OrderedDictionary với IDictionaryEnumerator

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        OrderedDictionary dict = new OrderedDictionary();
        dict.Add("1", "One");
        dict.Add("2", "Two");
        dict.Add("3", "Three");
        dict.Add("4", "Four");
        dict.Add("5", "Five");
        dict.Add("6", "Six");
        dict.Add("7", "Seven");
        dict.Add("8", "Eight");
        
        IDictionaryEnumerator demoEnum = dict.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }
    }
}

Kết quả

Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five
Key = 6, Value = Six
Key = 7, Value = Seven
Key = 8, Value = Eight

Ví dụ 2: OrderedDictionary với giá trị khác

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        OrderedDictionary dict = new OrderedDictionary();
        dict.Add("1", "Appliances");
        dict.Add("2", "Supplies");
        dict.Add("3", "Electronics");
        dict.Add("4", "Clothing");
        dict.Add("5", "Books");
        dict.Add("6", "Accessories");
        
        IDictionaryEnumerator demoEnum = dict.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
        }
    }
}

Kết quả

Key = 1, Value = Appliances
Key = 2, Value = Supplies
Key = 3, Value = Electronics
Key = 4, Value = Clothing
Key = 5, Value = Books
Key = 6, Value = Accessories

Các cách duyệt OrderedDictionary

OrderedDictionary dict = new OrderedDictionary();
// ... add items

// 1. IDictionaryEnumerator (cũ, từ ICollection)
IDictionaryEnumerator enum1 = dict.GetEnumerator();
while (enum1.MoveNext())
{
    Console.WriteLine($"{enum1.Key}: {enum1.Value}");
}

// 2. foreach trên DictionaryEntry (khuyên dùng)
foreach (DictionaryEntry entry in dict)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

// 3. Duyệt Keys
foreach (var key in dict.Keys)
{
    Console.WriteLine($"{key}: {dict[key]}");
}

// 4. Duyệt bằng chỉ mục (giữ thứ tự)
for (int i = 0; i < dict.Count; i++)
{
    Console.WriteLine($"{dict.GetKey(i)}: {dict[i]}");
}

Đặc điểm OrderedDictionary

  • Giữ thứ tự chèn (insertion order)
  • Truy cập bằng khóa: O(1)
  • Truy cập bằng chỉ mục: O(1)
  • Không generic - cân nhắc dùng Dictionary<TKey, TValue> + danh sách khóa riêng, hoặc thư viện OrderedDictionary<TKey, TValue>