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

Cách xóa phần tử khỏi ArrayList trong C#

Khai báo một ArrayList mới và thêm các phần tử vào đó.

ArrayList arr = new ArrayList();
arr.Add("One");
arr.Add("Two");
arr.Add("Three");
arr.Add("Four");

Giả sử bạn cần xóa phần tử "Three". Hãy sử dụng phương thức Remove().

arr.Remove("Three");

Dưới đây là ví dụ hoàn chỉnh để xóa một phần tử khỏi ArrayList:

Ví dụ

using System;
using System.Collections;

class Demo {
    static void Main() {
        ArrayList arr = new ArrayList();
        arr.Add("One");
        arr.Add("Two");
        arr.Add("Three");
        arr.Add("Four");
        Console.WriteLine("ArrayList...");
        foreach(string str in arr) {
            Console.WriteLine(str);
        }
        arr.Remove("Three");
        Console.WriteLine("ArrayList sau khi xóa phần tử...");
        foreach(string str in arr) {
            Console.WriteLine(str);
        }
        Console.ReadLine();
    }
}

Kết quả

ArrayList...
One
Two
Three
Four
ArrayList sau khi xóa phần tử...
One
Two
Four