Lớp List<T> cung cấp nhiều phương thức để xóa phần tử: theo giá trị (Remove), theo chỉ số (RemoveAt), theo điều kiện (RemoveAll), hoặc xóa hết (Clear).
Ví dụ: Xóa theo giá trị với Remove()
List myList = new List { "Jennings", "James", "Chris" };
myList.Remove("James"); // Xóa phần tử đầu tiên có giá trị "James"
// Kết quả: "Jennings", "Chris"
Mã nguồn hoàn chỉnh
using System.Collections.Generic;
using System;
class Program
{
static void Main()
{
List myList = new List();
myList.Add("Jennings");
myList.Add("James");
myList.Add("Chris");
Console.WriteLine("Danh sách ban đầu:");
foreach (string str in myList) Console.WriteLine(str);
myList.Remove("James");
Console.WriteLine("\nDanh sách sau khi xóa 'James':");
foreach (string str in myList) Console.WriteLine(str);
}
}
Kết quả
Danh sách ban đầu:
Jennings
James
Chris
Danh sách sau khi xóa 'James':
Jennings
Chris
Các phương thức xóa trong List<T>
| Phương thức | Mô tả | Trả về | Ví dụ |
|---|---|---|---|
Remove(T) | Xóa phần tử đầu tiên khớp giá trị | bool (đã xóa?) | list.Remove("A") |
RemoveAt(int) | Xóa tại chỉ số | void | list.RemoveAt(0) |
RemoveAll(Predicate) | Xóa tất cả thỏa điều kiện | int (số lượng đã xóa) | list.RemoveAll(x => x.Length > 5) |
RemoveRange(index, count) | Xóa một đoạn | void | list.RemoveRange(2, 3) |
Clear() | Xóa tất cả | void | list.Clear() |
Lưu ý quan trọng
Removechỉ xóa phần tử đầu tiên tìm thấy. DùngRemoveAllđể xóa tất cả.- Trả về
falsenếu không tìm thấy (không ném exception). - Duyệt và xóa cùng lúc: dùng
for (int i = list.Count - 1; i >= 0; i--)hoặcRemoveAll. RemoveAtnémArgumentOutOfRangeExceptionnếu index không hợp lệ.
Ví dụ RemoveAll
List numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int removed = numbers.RemoveAll(n => n % 2 == 0); // Xóa số chẵn
// numbers: 1, 3, 5, 7, 9
// removed: 4