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

Xóa mục tại chỉ số chỉ định khỏi OrderedDictionary trong C#

Giới thiệu

OrderedDictionary cho phép xóa phần tử tại một chỉ số cụ thể bằng phương thức RemoveAt(int index). Khác với Remove(key) xóa theo khóa, RemoveAt xóa theo vị trí (index) trong thứ tự chèn.

Ví dụ 1: Xóa tại chỉ số 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("Các phần tử của OrderedDictionary...");
        foreach (DictionaryEntry d in dict)
        {
            Console.WriteLine(d.Key + " " + d.Value);
        }
        Console.WriteLine("Số lượng phần tử trong OrderedDictionary = " + dict.Count);

        dict.RemoveAt(4); // Xóa phần tử tại chỉ số 4 (E - Clothing)

        Console.WriteLine("Số lượng phần tử trong OrderedDictionary (Đã cập nhật) = " + dict.Count);
    }
}

Kết quả

Các phần tử của OrderedDictionary...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
Số lượng phần tử trong OrderedDictionary = 6
Số lượng phần tử trong OrderedDictionary (Đã cập nhật) = 5

Ví dụ 2: Xóa tại chỉ số 1 và 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("Các phần tử của OrderedDictionary...");
        foreach (DictionaryEntry d in dict)
        {
            Console.WriteLine(d.Key + " " + d.Value);
        }
        Console.WriteLine("Số lượng phần tử trong OrderedDictionary = " + dict.Count);

        dict.RemoveAt(1); // Xóa "2" - "CD"
        dict.RemoveAt(2); // Xóa "4" - "PQ" (vì sau khi xóa chỉ số 1, "MN" thành chỉ số 1, "PQ" thành chỉ số 2)

        Console.WriteLine("Số lượng phần tử trong OrderedDictionary (Đã cập nhật) = " + dict.Count);
    }
}

Kết quả

Các phần tử của OrderedDictionary...
1 AB
2 CD
3 MN
4 PQ
Số lượng phần tử trong OrderedDictionary = 4
Số lượng phần tử trong OrderedDictionary (Đã cập nhật) = 2

Lưu ý: Chỉ số bắt đầu từ 0. Nếu chỉ số không hợp lệ (index < 0 hoặc index >= Count), phương thức ném ArgumentOutOfRangeException. Sau khi xóa, các phần tử sau sẽ dịch chuyển về trước.