📜  C#|从队列中删除所有对象

📅  最后修改于: 2021-05-29 15:58:00             🧑  作者: Mango

队列代表对象的先进先出集合。当您需要对项目进行先进先出的访问时,可以使用它。当您在列表中添加一个项目时,它称为enqueue ,而当您删除一个项目时,它称为deque队列。清除方法用于从队列中删除对象。此方法是O(n)运算,其中n是元素总数。

特性:

  • Enqueue将元素添加到队列的末尾。
  • 出队从队列开始处删除最旧的元素。
  • Peek返回位于队列开始处的最旧元素,但不会将其从队列中删除。
  • 队列的容量是队列可以容纳的元素数。
  • 随着元素添加到队列中,通过重新分配内部数组,容量会根据需要自动增加。
  • 队列接受null作为引用类型的有效值,并允许重复的元素。

句法 :

public virtual void Clear();

下面给出了一些示例,以更好地理解实现:

范例1:

// C# code to Remove all
// objects from the Queue
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Queue of strings
        Queue myQueue = new Queue();
  
        // Inserting the elements into the Queue
        myQueue.Enqueue("1st Element");
        myQueue.Enqueue("2nd Element");
        myQueue.Enqueue("3rd Element");
        myQueue.Enqueue("4th Element");
        myQueue.Enqueue("5th Element");
        myQueue.Enqueue("6th Element");
  
        // Displaying the count of elements
        // contained in the Queue before
        // removing all the elements
        Console.Write("Total number of elements in the Queue are : ");
  
        Console.WriteLine(myQueue.Count);
  
        // Removing all elements from Queue
        myQueue.Clear();
  
        // Displaying the count of elements
        // contained in the Queue after
        // removing all the elements
        Console.Write("Total number of elements in the Queue are : ");
  
        Console.WriteLine(myQueue.Count);
    }
}
输出:
Total number of elements in the Queue are : 6
Total number of elements in the Queue are : 0

范例2:

// C# code to Remove all
// objects from the Queue
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Queue of Integers
        Queue myQueue = new Queue();
  
        // Inserting the elements into the Queue
        myQueue.Enqueue(3);
        myQueue.Enqueue(5);
        myQueue.Enqueue(7);
        myQueue.Enqueue(9);
        myQueue.Enqueue(11);
  
        // Displaying the count of elements
        // contained in the Queue before
        // removing all the elements
        Console.Write("Total number of elements in the Queue are : ");
  
        Console.WriteLine(myQueue.Count);
  
        // Removing all elements from Queue
        myQueue.Clear();
  
        // Displaying the count of elements
        // contained in the Queue after
        // removing all the elements
        Console.Write("Total number of elements in the Queue are : ");
  
        Console.WriteLine(myQueue.Count);
    }
}
输出:
Total number of elements in the Queue are : 5
Total number of elements in the Queue are : 0

参考:

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