📌  相关文章
📜  C#|从列表中删除所有元素

📅  最后修改于: 2021-05-30 01:29:28             🧑  作者: Mango

列表类表示可以通过索引访问的对象列表。它位于System.Collection.Generic命名空间下。列表类可用于创建不同类型的集合,例如整数,字符串等。列表类还提供了搜索,排序和操作列表的方法。使用List.Clear方法从List中删除所有元素。

特性:

  • 它与数组不同。列表可以动态调整大小,但数组则不能。
  • List类可以接受null作为引用类型的有效值,并且还允许重复元素
  • 如果Count等于Capacity,则List的容量通过重新分配内部数组自动增加。在添加新元素之前,现有元素将被复制到新数组。

句法:

public void Clear ();

以下程序说明了如何从列表中删除所有元素:

范例1:

// C# program to remove all the
// elements from a List
using System;
using System.Collections.Generic;
  
class Geeks {
  
    // Main Method
    public static void Main()
    {
  
        // Creating a List of integers
        List list1 = new List();
  
        // Inserting the elements into the List
        list1.Add(1);
        list1.Add(4);
        list1.Add(3);
        list1.Add(1);
        list1.Add(2);
  
        // Displaying the count of elements
        // contained in the List before
        // removing all the elements
        Console.Write("Number of elements in the List Before Removing: ");
  
        // using Count property
        Console.WriteLine(list1.Count);
  
        // Removing all elements from list
        list1.Clear();
  
        // Displaying the count of elements
        // contained in the List after
        // removing all the elements
        Console.Write("Number of elements in the List After Removing: ");
  
        // using Count property
        Console.WriteLine(list1.Count);
    }
}

输出:

Number of elements in the List Before Removing: 5
Number of elements in the List After Removing: 0

范例2:

// C# program to remove all the
// elements from a List
using System;
using System.Collections.Generic;
  
class Geeks {
  
    // Main Method
    public static void Main()
    {
  
        // Creating a List of strings
        List list1 = new List();
  
        // Inserting the elements into the List
        list1.Add("Welcome");
        list1.Add("To");
        list1.Add("Geeks");
        list1.Add("for");
        list1.Add("Geeks");
        list1.Add("Geeks");
        list1.Add("Geeks");
  
        // Displaying the count of elements
        // contained in the List before
        // removing all the elements
        Console.Write("Number of elements in the List Before Removing: ");
  
        // using Count property
        Console.WriteLine(list1.Count);
  
        // Removing all elements from list
        list1.Clear();
  
        // Displaying the count of elements
        // contained in the List after
        // removing all the elements
        Console.Write("Number of elements in the List After Removing: ");
  
        // using Count property
        Console.WriteLine(list1.Count);
    }
}

输出:

Number of elements in the List Before Removing: 7
Number of elements in the List After Removing: 0

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.list-1.clear?view=netframework-4.7.2