Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เพิ่มอ็อบเจ็กต์ท้าย Queue - Enqueue Operation ใน C#

Queue<T> (ใน System.Collections.Generic) เป็นคอลเลกชันแบบ FIFO (First-In-First-Out) ใช้เมธอด Enqueue(T) เพิ่มอ็อบเจ็กต์ที่ท้ายคิว และ Dequeue() นำออกจากหน้าคิว

ตัวอย่างโค้ดที่ 1: Enqueue และ Contains

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Queue queue = new Queue();
        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: Clear และ Count

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Queue queue = new Queue();
        queue.Enqueue("Gary");
        queue.Enqueue("Jack");
        queue.Enqueue("Ryan");
        queue.Enqueue("Kevin");
        queue.Enqueue("Mark");
        queue.Enqueue("Jack"); // Duplicate allowed
        queue.Enqueue("Ryan");
        queue.Enqueue("Kevin");

        Console.Write("Count of elements = ");
        Console.WriteLine(queue.Count);

        queue.Clear();
        Console.Write("Count of elements (updated) = ");
        Console.WriteLine(queue.Count);
    }
}

ผลลัพธ์

Count of elements = 8
Count of elements (updated) = 0

เมธอดและ Property สำคัญของ Queue<T>

MemberคำอธิบายComplexity
Enqueue(T)เพิ่มที่ท้าย (rear)O(1) amortized
Dequeue()นำออกจากหน้า (front) และคืนค่าO(1)
Peek()ดูค่าหน้าคิว (ไม่ลบ)O(1)
CountจำนวนสมาชิกO(1)
Clear()ลบทั้งหมดO(n)
Contains(T)ตรวจสอบมีอยู่O(n)
ToArray()คัดลอกเป็น arrayO(n)
TrimExcess()ลด capacity ให้ใกล้ CountO(n)

ลำดับการวนลูป (Enumeration Order)

foreach บน Queue ให้ลำดับ Front to Rear (FIFO order) - ตัวที่ Enqueue ก่อนจะออกมาก่อน

Non-generic Queue (Legacy)

System.Collections.Queue - ควรหลีกเลี่ยง ใช้ Queue<T> แทน

Use Cases ของ Queue

  • BFS (Breadth-First Search) ใน graph/tree
  • Task scheduling / Job queue
  • Message queue / Producer-consumer pattern
  • Request processing (web server)
  • Print spooler
  • Keyboard buffer

ConcurrentQueue<T> - Thread-safe Version

สำหรับ multi-threaded scenarios ใช้ System.Collections.Concurrent.ConcurrentQueue<T> ซึ่งมี Enqueue, TryDequeue ที่ thread-safe