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

Xóa phần tử tại chỉ số chỉ định của ArrayList trong C#

Giới thiệu

Để xóa phần tử tại một chỉ số cụ thể trong ArrayList, bạn sử dụng phương thức RemoveAt(int index). Các phần tử sau vị trí bị xóa sẽ dịch chuyển về trước để lấp đầy khoảng trống.

Ví dụ 1: Xóa tại chỉ số 5

using System;
using System.Collections;

public class Demo
{
    public static void Main(String[] args)
    {
        ArrayList list1 = new ArrayList();
        list1.Add("A");
        list1.Add("B");
        list1.Add("C");
        list1.Add("D");
        list1.Add("E");
        list1.Add("F");
        list1.Add("G");
        list1.Add("H");
        list1.Add("I");

        Console.WriteLine("Các phần tử trong ArrayList1...");
        foreach (string res in list1)
            Console.WriteLine(res);

        ArrayList list2 = new ArrayList();
        list2.Add("A");
        list2.Add("B");
        list2.Add("C");
        list2.Add("D");
        list2.Add("E");
        list2.Add("F");
        list2.Add("G");
        list2.Add("H");
        list2.Add("I");

        Console.WriteLine("Các phần tử trong ArrayList2...");
        foreach (string res in list2)
            Console.WriteLine(res);

        Console.WriteLine("Số lượng phần tử trong ArrayList2 = " + list2.Count);
        list2.RemoveAt(5); // Xóa "F"
        Console.WriteLine("Số lượng phần tử trong ArrayList2 (Đã cập nhật) = " + list2.Count);
    }
}

Kết quả

Các phần tử trong ArrayList1...
A
B
C
D
E
F
G
H
I
Các phần tử trong ArrayList2...
A
B
C
D
E
F
G
H
I
Số lượng phần tử trong ArrayList2 = 9
Số lượng phần tử trong ArrayList2 (Đã cập nhật) = 8

Ví dụ 2: Xóa tại chỉ số 2

using System;
using System.Collections;

public class Demo
{
    public static void Main(String[] args)
    {
        ArrayList list1 = new ArrayList();
        list1.Add("Laptop");
        list1.Add("Dektop");
        list1.Add("Wearables");
        list1.Add("Tablet");
        list1.Add("Notebook");
        list1.Add("Ultrabooks");

        Console.WriteLine("Các phần tử trong ArrayList1...");
        foreach (string res in list1)
            Console.WriteLine(res);

        Console.WriteLine("Số lượng phần tử trong ArrayList = " + list1.Count);
        list1.RemoveAt(2); // Xóa "Wearables"
        Console.WriteLine("Số lượng phần tử trong ArrayList (Đã cập nhật) = " + list1.Count);
    }
}

Kết quả

Các phần tử trong ArrayList1...
Laptop
Dektop
Wearables
Tablet
Notebook
Ultrabooks
Số lượng phần tử trong ArrayList = 6
Số lượng phần tử trong ArrayList (Đã cập nhật) = 5

Lưu ý: ArrayList không kiểu an toàn (non-generic). Nên ưu tiên sử dụng List<T> trong code mới. RemoveAt ném ArgumentOutOfRangeException nếu chỉ số không hợp lệ.