Mục đích
Phương thức List<T>.RemoveAt(int index) xóa phần tử tại vị trí index (0-based). Các phần tử sau dịch trái. Ném ArgumentOutOfRangeException nếu index không hợp lệ.
Ví dụ 1: Xóa phần tử, duyệt bằng Enumerator
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main(string[] args)
{
List list = new List
{
"Ryan", "Kevin", "Andre", "Tom", "Fred", "Jason", "Jacob", "David"
};
Console.WriteLine($"Count: {list.Count}"); // 8
Console.WriteLine("\nDuyệt bằng Enumerator:");
List.Enumerator enumr = list.GetEnumerator();
while (enumr.MoveNext())
Console.WriteLine(enumr.Current);
// Xóa tại index 5 (Jason)
list.RemoveAt(5);
Console.WriteLine($"\nCount sau RemoveAt(5): {list.Count}"); // 7
Console.WriteLine("\nDuyệt lại (Updated):");
enumr = list.GetEnumerator();
while (enumr.MoveNext())
Console.WriteLine(enumr.Current);
}
}
Kết quả
Count: 8
Duyệt bằng Enumerator:
Ryan
Kevin
Andre
Tom
Fred
Jason
Jacob
David
Count sau RemoveAt(5): 7
Duyệt lại (Updated):
Ryan
Kevin
Andre
Tom
Fred
Jacob
David
Ví dụ 2: List xóa đơn giản
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main(string[] args)
{
List list = new List { 25, 50, 75, 100, 200 };
Console.WriteLine($"Count: {list.Count}"); // 5
list.RemoveAt(2); // Xóa 75
Console.WriteLine($"Count sau RemoveAt(2): {list.Count}"); // 4
Console.WriteLine("Remaining: " + string.Join(", ", list)); // 25, 50, 100, 200
}
}
Kết quả
Count: 5
Count sau RemoveAt(2): 4
Remaining: 25, 50, 100, 200
Phương thức xóa liên quan
| Phương thức | Mô tả | Trả về |
|---|---|---|
RemoveAt(index) | Xóa tại index | void |
Remove(item) | Xóa **phần tử đầu tiên** bằng giá trị (Equals) | bool (đã xóa?) |
RemoveAll(predicate) | Xóa tất cả thỏa predicate | int (số lượng xóa) |
Clear() | Xóa tất cả | void |
Lưu ý hiệu năng
RemoveAtlà O(n - index) do phải dịch chuyển mảng nội bộ.- Xóa ở đầu (index 0) chậm nhất. Xóa ở cuối (index = Count-1) nhanh nhất O(1).
- Nếu xóa nhiều lần trong vòng lặp, duyệt **ngược** (for i = Count-1 downto 0) hoặc dùng
RemoveAll. - Enumerator **không hỗ trợ** Remove (InvalidOperationException). Dùng for lùi hoặc List.RemoveAll.
Ví dụ: Xóa an toàn trong vòng lặp
List nums = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Cách 1: For lùi (an toàn)
for (int i = nums.Count - 1; i >= 0; i--)
{
if (nums[i] % 2 == 0) nums.RemoveAt(i);
}
// Cách 2: RemoveAll (khuyên dùng)
nums.RemoveAll(x => x % 2 == 0);
// Cách 3: LINQ Where (tạo list mới)
var odds = nums.Where(x => x % 2 != 0).ToList();