คลาส Queue ใน C#
Queue เป็นคอลเลกชันแบบ First-In-First-Out (FIFO) หรือเข้าก่อนออกก่อน ใช้เมื่อต้องการเข้าถึงข้อมูลตามลำดับที่เพิ่มเข้าไป อยู่ใน namespace System.Collections (non-generic) และ System.Collections.Generic (generic Queue<T>)
เมธอดหลักของ Queue
| เมธอด | คำอธิบาย |
|---|---|
Enqueue(item) |
เพิ่มรายการไปท้ายคิว |
Dequeue() |
นำรายการหน้าสุดออกและคืนค่า |
Peek() |
ดูรายการหน้าสุดโดยไม่นำออก |
Contains(item) |
ตรวจสอบว่ามีรายการในคิวหรือไม่ |
Clear() |
ล้างรายการทั้งหมดในคิว |
Count |
คุณสมบัติ: จำนวนรายการในคิว |
ตัวอย่างโค้ด (Non-generic)
using System;
using System.Collections;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Queue q = new Queue();
q.Enqueue('X');
q.Enqueue('Y');
q.Enqueue('Z');
Console.WriteLine("คิวปัจจุบัน: ");
foreach (char c in q) Console.Write(c + " ");
Console.WriteLine();
q.Enqueue('A');
Console.WriteLine("คิวปัจจุบัน: ");
foreach (char c in q) Console.Write(c + " ");
Console.WriteLine();
Console.ReadKey();
}
}
}
ผลลัพธ์
คิวปัจจุบัน: X Y Z
คิวปัจจุบัน: X Y Z A
ตัวอย่างแบบ Generic (แนะนำ)
using System;
using System.Collections.Generic;
Queue queue = new Queue();
queue.Enqueue("First");
queue.Enqueue("Second");
queue.Enqueue("Third");
Console.WriteLine(queue.Dequeue()); // First
Console.WriteLine(queue.Peek()); // Second (ยังอยู่ในคิว)
Console.WriteLine(queue.Count); // 2
กรณีการใช้งานทั่วไป
- จัดการงานแบบคิว (Task scheduling)
- Breadth-First Search (BFS) ในกราฟ
- Buffer สำหรับ Producer-Consumer pattern
- จัดการคำสั่งซื้อ/คำขอตามลำดับ