當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C# Queue.Clear用法及代碼示例


此方法用於從隊列中刪除對象。此方法是O(n)運算,其中n是元素總數。而且此方法位於System.Collections命名空間下。

用法:

public void Clear ();

下麵給出了一些示例,以更好地理解實現:


示例1:

// C# code to illustrate the 
// Queue.Clear Method 
using System; 
using System.Collections; 
  
class GFG { 
  
    // Driver code 
    public static void Main() 
    { 
  
        // Creating a Queue 
        Queue q = new Queue(); 
  
        // Inserting the elements into the Queue 
        q.Enqueue(1); 
        q.Enqueue(2); 
        q.Enqueue(2); 
        q.Enqueue(4); 
  
        // 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(q.Count); 
  
        // Removing all elements from Queue 
        q.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(q.Count); 
    } 
}
輸出:
Total number of elements in the Queue are : 4
Total number of elements in the Queue are : 0

示例2:

// C# code to illustrate the 
// Queue.Clear Method 
using System; 
using System.Collections; 
  
class GFG { 
  
    // Driver code 
    public static void Main() 
    { 
  
        // Creating a Queue 
        Queue q = new Queue(); 
   
        // Inserting the elements into the Queue 
        q.Enqueue("C"); 
        q.Enqueue("C++"); 
        q.Enqueue("Java"); 
        q.Enqueue("PHP"); 
        q.Enqueue("HTML"); 
        q.Enqueue("Python"); 
  
        // 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(q.Count); 
  
        // Removing all elements from Queue 
        q.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(q.Count); 
    } 
}
輸出:
Total number of elements in the Queue are : 6
Total number of elements in the Queue are : 0

參考:



相關用法


注:本文由純淨天空篩選整理自Twinkl Bajaj大神的英文原創作品 Queue.Clear Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。