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

ดึง IDictionaryEnumerator จาก OrderedDictionary ใน C#

ภาพรวม

OrderedDictionary.GetEnumerator() คืนค่า IDictionaryEnumerator ใช้วนลูปผ่านคู่คีย์-ค่าในลำดับที่เพิ่ม (insertion order) ต่างจาก Hashtable ที่ไม่รักษาลำดับ

ตัวอย่างที่ 1: วนลูป OrderedDictionary ด้วย 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);
        }
    }
}

ผลลัพธ์

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

ตัวอย่างที่ 2: OrderedDictionary อีกตัวหนึ่ง

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);
        }
    }
}

ผลลัพธ์

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

คำอธิบายเพิ่มเติม

  • IDictionaryEnumerator มีคุณสมบัติ Key, Value, Entry (DictionaryEntry) และเมธอด MoveNext(), Reset()
  • OrderedDictionary รักษาลำดับการเพิ่ม (insertion order) เหมาะสำหรับการแสดงผลที่ต้องการลำดับคงที่
  • สามารถใช้ foreach (DictionaryEntry de in dict) แทน GetEnumerator() ได้ง่ายกว่า
  • คีย์ต้องเป็น unique คีย์ซ้ำโยน ArgumentException
  • OrderedDictionary เป็น non-generic สำหรับโค้ดใหม่ พิจารณาสร้าง wrapper generic เองหรือใช้ third-party