Khai báo 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" );
Bây giờ, giả sử bạn cần xóa phần tử “Ba”. Để làm điều đó, hãy sử dụng phương thức Remove ().
arr.Remove("Three"); Sau đâ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 after removing an element...");
foreach(string str in arr) {
Console.WriteLine(str);
}
Console.ReadLine();
}
} Đầu ra
ArrayList... One Two Three Four ArrayList after removing an element... One Two Four