คิว (Queue) ใน C# - First-In-First-Out (FIFO)
Queue เป็นคอลเลกชันที่ทำงานแบบ FIFO: องค์ประกอบที่เพิ่มเข้ามาก่อนจะถูกนำออกไปก่อน ใช้ namespace System.Collections (non-generic) หรือ System.Collections.Generic (generic Queue<T>)
อินเทอร์เฟซและเมธอดหลัก
| เมธอด | คำอธิบาย | คืนค่า |
|---|---|---|
Enqueue(T item) | เพิ่มรายการเข้าคิว (ท้ายคิว) | void |
Dequeue() | นำรายการออกจากคิว (หัวคิว) และคืนค่า | T |
Peek() | ดูรายการหัวคิวโดยไม่นำออก | T |
Count | จำนวนรายการในคิว | int |
Clear() | ล้างคิวทั้งหมด | void |
Contains(T item) | ตรวจสอบว่ามีรายการในคิวหรือไม่ | bool |
ตัวอย่าง: ใช้ Queue<T> (Generic - แนะนำ)
using System;
using System.Collections.Generic;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Queue queue = new Queue();
// Enqueue - เพิ่มข้อมูล
queue.Enqueue("First");
queue.Enqueue("Second");
queue.Enqueue("Third");
Console.WriteLine($"จำนวนในคิว: {queue.Count}"); // 3
Console.WriteLine($"หัวคิว (Peek): {queue.Peek()}"); // First
// วนลูปแสดง (ไม่ลบ)
Console.WriteLine("คิวปัจจุบัน:");
foreach (string item in queue)
Console.WriteLine(item);
// Dequeue - นำออกทีละตัว
Console.WriteLine("\nนำออกทีละตัว (Dequeue):");
while (queue.Count > 0)
{
string item = queue.Dequeue();
Console.WriteLine($"Dequeued: {item}, เหลือ: {queue.Count}");
}
Console.ReadKey();
}
}
}
ผลลัพธ์
จำนวนในคิว: 3
หัวคิว (Peek): First
คิวปัจจุบัน:
First
Second
Third
นำออกทีละตัว (Dequeue):
Dequeued: First, เหลือ: 2
Dequeued: Second, เหลือ: 1
Dequeued: Third, เหลือ: 0
Non-generic Queue (เก่า)
using System.Collections;
Queue q = new Queue();
q.Enqueue('X');
q.Enqueue('Y');
q.Enqueue('Z');
// ต้อง cast ตอนนำออก
char c = (char)q.Dequeue();
กรณีใช้งานจริง (Use Cases)
- Task Scheduling: จัดลำดับงาน (print queue, job queue)
- BFS (Breadth-First Search): การค้นหาในกราฟ/ต้นไม้
- Message Queue: ระบบข้อความแบบ asynchronous
- Buffer/Streaming: จัดการข้อมูลสตรีม (audio, video)
- Undo/Redo (จำกัด): เก็บประวัติการกระทำ
ConcurrentQueue - Thread-Safe Version
using System.Collections.Concurrent;
var concurrentQueue = new ConcurrentQueue();
concurrentQueue.Enqueue(1);
concurrentQueue.TryDequeue(out int result); // ไม่โยน exception
แนะนำ: ใช้ Queue<T> (generic) แทน Queue (non-generic) เพื่อ type safety และประสิทธิภาพ (ไม่ต้อง boxing/unboxing)