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

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

Giới thiệu

List<T> (namespace System.Collections.Generic) là danh sách động kiểu mạnh. Phương thức Clear() xóa tất cả phần tử, đặt Count về 0 nhưng giữ nguyên Capacity.

Ví dụ 1: Xóa phần tử từ List và so sánh

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main(String[] args)
    {
        List<String> list1 = new List<String>();
        list1.Add("One");
        list1.Add("Two");
        list1.Add("Three");
        list1.Add("Four");
        list1.Add("Five");
        
        Console.WriteLine("Elements in List1...");
        foreach (string res in list1)
        {
            Console.WriteLine(res);
        }
        
        List<String> list2 = new List<String>();
        list2.Add("India");
        list2.Add("US");
        list2.Add("UK");
        list2.Add("Canada");
        list2.Add("Poland");
        list2.Add("Netherlands");
        
        Console.WriteLine("Elements in List2...");
        foreach (string res in list2)
        {
            Console.WriteLine(res);
        }
        
        Console.WriteLine("\nIs List2 equal to List1? = " + list2.Equals(list1));
        Console.WriteLine("\nCount of elements in list2 = " + list2.Count);
        
        list2.Clear();
        
        Console.WriteLine("\nCount of elements in list2 (updated) = " + list2.Count);
    }
}

Kết quả

Elements in List1...
One
Two
Three
Four
Five
Elements in List2...
India
US
UK
Canada
Poland
Netherlands
Is List2 equal to List1? = False
Count of elements in list2 = 6
Count of elements in list2 (updated) = 0

Ví dụ 2: Xóa và quan sát Capacity

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main(String[] args)
    {
        List<String> list = new List<String>();
        list.Add("One");
        list.Add("Two");
        list.Add("Three");
        list.Add("Four");
        list.Add("Five");
        
        Console.WriteLine("Elements in List...");
        foreach (string res in list)
        {
            Console.WriteLine(res);
        }
        
        Console.WriteLine("\nCount of elements in list = " + list.Count);
        Console.WriteLine("Capacity before Clear = " + list.Capacity);
        
        list.Clear();
        
        Console.WriteLine("\nCount of elements in list (updated) = " + list.Count);
        Console.WriteLine("Capacity after Clear = " + list.Capacity);
    }
}

Kết quả

Elements in List...
One
Two
Three
Four
Five
Count of elements in list = 5
Capacity before Clear = 8
Count of elements in list (updated) = 0
Capacity after Clear = 8

Lưu ý quan trọng

  • Clear() chỉ đặt Count = 0, không giải phóng bộ nhớ (Capacity không đổi)
  • Để giải phóng bộ nhớ, gán list = new List<T>() hoặc gọi list.TrimExcess()
  • Phương thức này có độ phức tạp O(n) do phải đặt các tham chiếu về null