คลาส Queue<T> ในเนมสเปซ System.Collections.Generic เป็นคอลเลกชันแบบ First-In-First-Out (FIFO) องค์ประกอบที่เพิ่มเข้าก่อนจะถูกนำออกก่อน เหมือนคิวคนรอซื้อตั๋วหนัง
เมธอดหลัก
- Enqueue(T item) - เพิ่มองค์ประกอบเข้าไปที่ท้ายคิว
- Dequeue() - นำองค์ประกอบที่หัวคิวออกและส่งคืนค่า
- Peek() - ดูองค์ประกอบหัวคิวโดยไม่เอาออก
- Count - จำนวนองค์ประกอบในคิว
ตัวอย่างการใช้งาน
using System;
using System.Collections.Generic;
class Demo
{
static void Main()
{
Queue q = new Queue();
// Enqueue - เพิ่มข้อมูล
q.Enqueue("First");
q.Enqueue("Second");
q.Enqueue("Third");
Console.WriteLine($"จำนวนในคิว: {q.Count}"); // 3
Console.WriteLine($"หัวคิว: {q.Peek()}"); // First
// Dequeue - นำออกตามลำดับ FIFO
while (q.Count > 0)
{
Console.WriteLine($"Dequeue: {q.Dequeue()}");
}
// ผลลัพธ์: First, Second, Third
}
}
ผลลัพธ์
จำนวนในคิว: 3 หัวคิว: First Dequeue: First Dequeue: Second Dequeue: Third
การใช้งานจริง
- Task Scheduling / Job Queue
- Breadth-First Search (BFS)
- Message Processing Pipeline
- Print Queue, Request Queue
หมายเหตุ: มี Queue (Non-generic) ใน System.Collections และ Queue<T> (Generic) ใน System.Collections.Generic ควรใช้ Generic version