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

วิธีลบรายการตามคีย์ที่ระบุจาก OrderedDictionary ใน C#

บทความนี้สาธิตวิธีการลบรายการ (entry) ตามคีย์ที่ระบุจาก OrderedDictionary โดยใช้ method Remove(object key)

ตัวอย่างที่ 1: ลบคีย์ "E"

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 elements...");
        foreach (DictionaryEntry d in dict)
        {
            Console.WriteLine(d.Key + " " + d.Value);
        }

        Console.WriteLine("Count of elements in OrderedDictionary = " + dict.Count);

        dict.Remove("E");

        Console.WriteLine("Count of elements in OrderedDictionary (Updated) = " + dict.Count);
    }
}

ผลลัพธ์

OrderedDictionary elements...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
Count of elements in OrderedDictionary = 6
Count of elements in OrderedDictionary (Updated) = 5

ตัวอย่างที่ 2: ลบหลายคีย์ติดต่อกัน

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

public class Demo
{
    public static void Main()
    {
        OrderedDictionary dict = new OrderedDictionary();
        dict.Add("A", "One");
        dict.Add("B", "Two");
        dict.Add("C", "Three");
        dict.Add("D", "Four");

        Console.WriteLine("OrderedDictionary elements...");
        foreach (DictionaryEntry d in dict)
        {
            Console.WriteLine(d.Key + " " + d.Value);
        }

        Console.WriteLine("Count of elements in OrderedDictionary = " + dict.Count);

        dict.Remove("C");
        dict.Remove("D");

        Console.WriteLine("Count of elements in OrderedDictionary (Updated) = " + dict.Count);
    }
}

ผลลัพธ์

OrderedDictionary elements...
A One
B Two
C Three
D Four
Count of elements in OrderedDictionary = 4
Count of elements in OrderedDictionary (Updated) = 2

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

  • Remove(object key) ลบรายการที่มีคีย์ตรงกับที่ระบุ คืนค่า void
  • ถ้าคีย์ไม่มีอยู่ จะไม่เกิด error - silent ignore
  • Key เป็น object - สามารถเป็นชนิดข้อมูลใดก็ได้ (แต่ต้อง match ชนิดที่เพิ่มเข้าไป)
  • OrderedDictionary รักษา insertion order - ลำดับไม่เปลี่ยนเมื่อลบ (แค่รายการหายไป)
  • มี method RemoveAt(int index) สำหรับลบตามดัชนีอีกวิธี
  • เวลา complexity: O(n) - ต้องค้นหาคีย์ก่อน (linear search) แล้วเลื่อน array
  • เป็น legacy class - โค้ดใหม่ควรใช้ Dictionary<TKey, TValue> + แยกเก็บลำดับหรือใช้ OrderedDictionary<TKey, TValue> (third-party)