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

ลบองค์ประกอบทั้งหมดจาก OrderedDictionary ใน C#

เมธอด Clear() ของ OrderedDictionary ใช้ลบคู่คีย์-ค่าทั้งหมด ทำให้ Count กลายเป็น 0 แต่ยังคงลำดับการแทรก (Insertion Order) สำหรับการเพิ่มใหม่

ตัวอย่างที่ 1: OrderedDictionary พื้นฐาน

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

public class Demo
{
    public static void Main()
    {
        OrderedDictionary dict = new OrderedDictionary();
        dict.Add("A", "Books");
        dict.Add("B", "Electronics");
        dict.Add("C", "Smart Wearables");
        dict.Add("D", "Pet Supplies");
        dict.Add("E", "Clothing");
        dict.Add("F", "Footwear");

        Console.WriteLine("OrderedDictionary องค์ประกอบ...");
        foreach (DictionaryEntry d in dict)
        {
            Console.WriteLine(d.Key + " " + d.Value);
        }

        Console.WriteLine("จำนวนองค์ประกอบใน OrderedDictionary = " + dict.Count); // 6

        // ลบทั้งหมด
        dict.Clear();

        Console.WriteLine("จำนวนองค์ประกอบใน OrderedDictionary (อัปเดต) = " + dict.Count); // 0
    }
}

ผลลัพธ์ (รักษาลำดับการแทรก)

OrderedDictionary องค์ประกอบ...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
จำนวนองค์ประกอบใน OrderedDictionary = 6
จำนวนองค์ประกอบใน OrderedDictionary (อัปเดต) = 0

ตัวอย่างที่ 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", "AB");
        dict.Add("2", "CD");

        Console.WriteLine("OrderedDictionary องค์ประกอบ...");
        foreach (DictionaryEntry d in dict)
        {
            Console.WriteLine(d.Key + " " + d.Value);
        }

        Console.WriteLine("จำนวนองค์ประกอบใน OrderedDictionary = " + dict.Count); // 2

        dict.Clear();

        Console.WriteLine("จำนวนองค์ประกอบใน OrderedDictionary (อัปเดต) = " + dict.Count); // 0
    }
}

ผลลัพธ์

OrderedDictionary องค์ประกอบ...
1 AB
2 CD
จำนวนองค์ประกอบใน OrderedDictionary = 2
จำนวนองค์ประกอบใน OrderedDictionary (อัปเดต) = 0

คุณสมบัติพิเศษของ OrderedDictionary

คุณสมบัติ/เมธอดคำอธิบาย
Clear()ลบคู่คีย์-ค่าทั้งหมด
Countจำนวนคู่คีย์-ค่า
[key]เข้าถึงค่าผ่านคีย์ (Indexer)
Keysคอลเลกชันคีย์ (ICollection)
Valuesคอลเลกชันค่า (ICollection)
AsReadOnly()สร้าง Wrapper แบบ Read-Only
Insert(int index, key, value)แทรกที่ตำแหน่งเฉพาะ (รักษาลำดับ)
RemoveAt(int index)ลบที่ดัชนีเฉพาะ

ข้อสังเกต

  • OrderedDictionary รักษา ลำดับการแทรก (Insertion Order) ไม่ใช่เรียงตามคีย์
  • ต่างจาก SortedDictionary ที่เรียงตามคีย์ และ Dictionary ที่ไม่รับประกันลำดับ
  • เป็น Non-generic ใช้ object สำหรับ Key และ Value
  • สำหรับโค้ดใหม่ พิจารณา Dictionary<TKey, TValue> (ไม่สนลำดับ) หรือสร้างเองด้วย List<KeyValuePair<TKey, TValue>> หากต้องการลำดับ
  • .NET 6+ มี OrderedDictionary<TKey, TValue> ใน System.Collections.Generic (Preview/Experimental)