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

วิธีดึงออบเจ็กต์ที่จุดเริ่มต้นของ Queue แบบ Peek ใน C#

บทความนี้สาธิตวิธีการดูออบเจ็กต์ที่จุดเริ่มต้น (front) ของ Queue<T> โดยไม่ลบออก โดยใช้ method Peek()

ตัวอย่างที่ 1: Peek คิว 7 รายการ

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Queue<string> queue = new Queue<string>();
        queue.Enqueue("A");
        queue.Enqueue("B");
        queue.Enqueue("C");
        queue.Enqueue("D");
        queue.Enqueue("E");
        queue.Enqueue("F");
        queue.Enqueue("G");

        Console.WriteLine("Count of elements = " + queue.Count);
        Console.WriteLine("Element at the beginning of queue = " + queue.Peek());
    }
}

ผลลัพธ์

Count of elements = 7
Element at the beginning of queue = A

ตัวอย่างที่ 2: Peek หลังเพิ่มข้อมูลเพิ่ม

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Queue<string> queue = new Queue<string>();
        queue.Enqueue("A");
        queue.Enqueue("B");
        queue.Enqueue("C");
        queue.Enqueue("D");
        queue.Enqueue("E");
        queue.Enqueue("F");
        queue.Enqueue("G");

        Console.WriteLine("Count of elements = " + queue.Count);
        Console.WriteLine("Element at the beginning of queue = " + queue.Peek());

        queue.Enqueue("H");
        queue.Enqueue("I");
        queue.Enqueue("J");

        Console.WriteLine("Count of elements = " + queue.Count);
        Console.WriteLine("Element at the beginning of queue = " + queue.Peek());
    }
}

ผลลัพธ์

Count of elements = 7
Element at the beginning of queue = A
Count of elements = 10
Element at the beginning of queue = A

คำอธิบายเพิ่มเติม

  • Peek() คืนค่าที่จุดเริ่มต้นของคิว (front) โดยไม่ลบออก
  • ถ้าคิวว่าง จะโยน InvalidOperationException
  • ต่างจาก Dequeue() ที่คืนค่าและลบออกจากคิว
  • Queue เป็น FIFO (First-In-First-Out) - ตัวแรกที่เข้า ตัวแรกที่ออก
  • เวลา complexity: O(1) - เข้าถึง head pointer โดยตรง
  • Generic Queue<T> type-safe และเร็วกว่า Queue (non-generic) ที่ต้อง boxing/unboxing
  • มี TryPeek(out T result) ใน .NET Core/.NET 5+ สำหรับไม่โยน exception