คุณสมบัติ Queue.Count ใน C# ใช้สำหรับดึงจำนวนองค์ประกอบ ที่อยู่ใน Queue ปัจจุบัน คืนค่าจำนวนเต็ม (int)
ไวยากรณ์ (Syntax)
public virtual int Count { get; }
ตัวอย่างที่ 1: Queue<int> กับ Clear
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Queue queue = new Queue();
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(900);
queue.Enqueue(1000);
Console.WriteLine("Queue...");
foreach (int i in queue)
{
Console.WriteLine(i);
}
Console.WriteLine("Count of elements in the Queue = " + queue.Count);
queue.Clear();
Console.WriteLine("Count of elements in the Queue [Updated] = " + queue.Count);
}
}
ผลลัพธ์
Queue... 100 200 300 400 500 600 700 800 900 1000 Count of elements in the Queue = 10 Count of elements in the Queue [Updated] = 0
ตัวอย่างที่ 2: เพิ่มและล้างคิว
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Queue queue = new Queue();
queue.Enqueue(100);
queue.Enqueue(200);
queue.Enqueue(300);
Console.WriteLine("Queue...");
foreach (int i in queue)
{
Console.WriteLine(i);
}
Console.WriteLine("Count of elements in the Queue = " + queue.Count);
queue.Enqueue(800);
queue.Enqueue(900);
queue.Enqueue(1000);
Console.WriteLine("Count of elements in the Queue [Updated] = " + queue.Count);
queue.Clear();
Console.WriteLine("Count of elements in the Queue [Updated] = " + queue.Count);
}
}
ผลลัพธ์
Queue... 100 200 300 Count of elements in the Queue = 3 Count of elements in the Queue [Updated] = 6 Count of elements in the Queue [Updated] = 0
ข้อสังเกตสำคัญ
Countเป็นคุณสมบัติ read-only — อัปเดตอัตโนมัติเมื่อ Enqueue, Dequeue, Clear- การเข้าถึง Count เป็น O(1) — เร็วมาก
- ควรตรวจสอบ
Count > 0ก่อนเรียกDequeue()หรือPeek() - Queue<T> (Generic) และ Queue (Non-generic) ทั้งคู่มี Count property
- ต่างจาก Stack.Count เพียงแค่โครงสร้างข้อมูล (FIFO vs LIFO) — Count ทำงานเหมือนกัน