C#|从列表中删除所有元素

列表 类表示可以通过索引访问的对象列表。它属于 系统收集通用的 名称空间。List类可用于创建不同类型的集合,如整数、字符串等。List类还提供搜索、排序和操作列表的方法。 列表清晰的方法 用于从列表中删除所有元素。

null

属性:

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

语法:

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< int > list1 = new List< int >();
// 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< string > list1 = new List< string >();
// 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

参考:

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享