C#从ArrayList中删除所有元素

2021年5月8日16:21:58 发表评论 642 次浏览

数组列表表示可以单独索引的对象的有序集合。它基本上是数组的替代方法。它还允许动态分配内存, 添加, 搜索和排序列表中的项目。ArrayList.Clear方法用于从ArrayList中删除所有元素。

特性:

  • 可以随时在数组列表集合中添加或删除元素。
  • 不能保证对ArrayList进行排序。
  • ArrayList的容量是ArrayList可以容纳的元素数。
  • 可以使用整数索引访问此集合中的元素。此集合中的索引从零开始。
  • 它还允许重复的元素。
  • 不支持将多维数组用作ArrayList集合中的元素。

语法如下:

public virtual void Clear ();

例外情况:这种方法会给NotSupportedException如果ArrayList为只读或ArrayList具有固定大小。

注意:

  • 此方法是O(n)运算, 其中n是Count。
  • Count设置为零, 并且还释放对集合元素中其他对象的引用。
  • 容量保持不变。

下面的程序说明了ArrayList.Clear方法的用法:

示例1:

//C# code to remove all elements
//from an ArrayList
using System;
using System.Collections;
  
class GFG {
  
     //Driver code
     public static void Main()
     {
  
         //Creating an ArrayList
         ArrayList myList = new ArrayList(10);
  
         //Adding elements to ArrayList
         myList.Add( "A" );
         myList.Add( "B" );
         myList.Add( "C" );
         myList.Add( "D" );
         myList.Add( "E" );
         myList.Add( "F" );
  
         //Displaying the elements in ArrayList
         Console.WriteLine( "Number of elements in ArrayList initially : " 
                                                         + myList.Count);
  
         //Removing all elements from ArrayList
         myList.Clear();
  
         //Displaying the elements in ArrayList
         //after Removing all the elements
         Console.WriteLine( "Number of elements in ArrayList : " + myList.Count);
     }
}

输出如下:

Number of elements in ArrayList initially : 6
Number of elements in ArrayList : 0

示例2:

//C# code to remove all elements
//from an ArrayList
using System;
using System.Collections;
  
  
class GFG {
  
     //Driver code
     public static void Main()
     {
  
         //Creating an ArrayList
         ArrayList myList = new ArrayList(10);
  
         //Adding elements to ArrayList
         myList.Add(3);
         myList.Add(5);
         myList.Add(7);
         myList.Add(9);
         myList.Add(11);
  
         //Displaying the elements in ArrayList
         Console.WriteLine( "Number of elements in ArrayList initially : " 
                                                         + myList.Count);
  
         //Removing all elements from ArrayList
         myList.Clear();
  
         //Displaying the elements in ArrayList
         //after Removing all the elements
         Console.WriteLine( "Number of elements in ArrayList : " + myList.Count);
     }
}

输出如下:

Number of elements in ArrayList initially : 5
Number of elements in ArrayList : 0

参考:

  • https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.clear?view=netframework-4.7.2

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: