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

Xóa phần tử khỏi List trong C#

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ứcMô 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ốvoidlist.RemoveAt(0)
RemoveAll(Predicate)Xóa tất cả thỏa điều kiệnint (số lượng đã xóa)list.RemoveAll(x => x.Length > 5)
RemoveRange(index, count)Xóa một đoạnvoidlist.RemoveRange(2, 3)
Clear()Xóa tất cảvoidlist.Clear()

Lưu ý quan trọng

  • Remove chỉ xóa phần tử đầu tiên tìm thấy. Dùng RemoveAll để xóa tất cả.
  • Trả về false nế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ặc RemoveAll.
  • RemoveAt ném ArgumentOutOfRangeException nế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