在 C# 中检查元素是否在队列里


要檢查某元素是否在佇列中,程式碼如下 −

範例

 線上範例

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Queue<string> queue = new Queue<string>();
      queue.Enqueue("Electronics");
      queue.Enqueue("Accessories");
      queue.Enqueue("Toys");
      queue.Enqueue("Books");
      queue.Enqueue("Furniture");
      queue.Enqueue("Clothing");
      queue.Enqueue("Footwear");
      queue.Enqueue("Cookware");
      queue.Enqueue("Pet Supplies");
      Console.WriteLine("Elements in the Queue...");
      foreach(var element in queue){
         Console.WriteLine(element);
      }
      Console.WriteLine("Do the queue has the element Books? = "+queue.Contains("Books"));
   }
}

輸出

將產生下列輸出 −

Elements in the Queue...
Electronics
Accessories
Toys
Books
Furniture
Clothing
Footwear
Cookware
Pet Supplies
Do the queue has the element Books? = True

範例

我們來看另一個範例 −

 線上範例

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Queue<int> queue = new Queue<int>();
      queue.Enqueue(100);
      queue.Enqueue(200);
      queue.Enqueue(300);
      queue.Enqueue(400);
      queue.Enqueue(500);
      queue.Enqueue(600);
      queue.Enqueue(700);
      queue.Enqueue(800);
      queue.Enqueue(1000);
      Console.WriteLine("Elements in the Queue...");
      foreach(var element in queue){
         Console.WriteLine(element);
      }
      Console.WriteLine("Do the queue has the element 50? = "+queue.Contains(50));
   }
}

輸出

將產生下列輸出 −

Elements in the Queue...
100
200
300
400
500
600
700
800
1000
Do the queue has the element 50? = False

更新日期: 2019 年 12 月 4 日

158 次檢視

開啟您的 職業生涯

完成課程以取得認證

開始學習
广告
© . All rights reserved.