บทความนี้สาธิตวิธีตรวจสอบว่า Queue<T> มีสมาชิก (element) ที่ระบุอยู่หรือไม่ โดยใช้เมธอด Contains() ใน C#
ตัวอย่างที่ 1: ตรวจสอบสมาชิกใน Queue ของสตริง (พบ)
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
ตัวอย่างที่ 2: ตรวจสอบสมาชิกใน Queue ของจำนวนเต็ม (ไม่พบ)
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
สรุป
- ใช้
Contains(T item)เพื่อตรวจสอบว่ามีสมาชิกอยู่ใน Queue หรือไม่ — คืนค่าbool - Queue เป็นโครงสร้างข้อมูลแบบ FIFO (First In, First Out) — สมาชิกที่เพิ่มเข้าไปก่อนจะถูกนำออกก่อน
- การวนลูป
foreachแสดงข้อมูลตามลำดับ FIFO (front ไป back) - เมธอด
Contains()ทำการค้นหาแบบ linear search — Complexity คือ O(n) - เมธอดหลักของ Queue:
Enqueue()(เพิ่ม),Dequeue()(นำออก),Peek()(ดูข้างหน้า),Contains()(ค้นหา)