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

วิธีลบรายการที่ดัชนีที่ระบุจาก OrderedDictionary ใน C#

บทความนี้สาธิตวิธีการลบรายการ (entry) ที่ดัชนี (index) ที่ระบุจาก OrderedDictionary โดยใช้ method RemoveAt(int index)

ตัวอย่างที่ 1: ลบรายการที่ดัชนี 4

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.RemoveAt(4); // ลบ index 4 (E Clothing)

        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("1", "AB");
        dict.Add("2", "CD");
        dict.Add("3", "MN");
        dict.Add("4", "PQ");

        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.RemoveAt(1); // ลบ index 1 (2 CD)
        dict.RemoveAt(2); // ลบ index 2 เดิม (ตอนนี้คือ 4 PQ เพราะเลื่อนมา)

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

ผลลัพธ์

OrderedDictionary elements...
1 AB
2 CD
3 MN
4 PQ
Count of elements in OrderedDictionary = 4
Count of elements in OrderedDictionary (Updated) = 2

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

  • RemoveAt(int index) ลบรายการที่ดัชนีที่ระบุ (0-based) ตาม insertion order
  • โยน ArgumentOutOfRangeException ถ้าดัชนีอยู่นอกช่วง (น้อยกว่า 0 หรือ มากกว่าหรือเท่ากับ Count)
  • หลังลบแล้ว รายการถัดๆ ไปจะเลื่อนมาทับตำแหน่ง (shift left)
  • OrderedDictionary รักษา insertion order และเข้าถึงได้ทั้งโดย key และ index
  • มี method Remove(key) สำหรับลบตามคีย์อีกวิธีหนึ่ง
  • เวลา complexity: O(n) - ต้องเลื่อนข้อมูลหลังตำแหน่งที่ลบ