Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Thêm đối tượng vào cuối Queue (Enqueue) trong C#

Giới thiệu

Queue<T> (namespace System.Collections.Generic) là hàng đợi FIFO (First-In-First-Out). Phương thức Enqueue(T item) thêm phần tử vào cuối hàng đợi.

Ví dụ 1: Enqueue 8 chuỗi, kiểm tra 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("Các phần tử trong Queue...");
        foreach (var element in queue)
        {
            Console.WriteLine(element);
        }

        Console.WriteLine("Queue có phần tử 'Books'? = " + queue.Contains("Books"));
    }
}

Kết quả

Các phần tử trong Queue...
Electronics
Accessories
Toys
Books
Furniture
Clothing
Footwear
Cookware
Pet Supplies
Queue có phần tử 'Books'? = True

Ví dụ 2: Enqueue, 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"); // trùng lặp cho phép
        queue.Enqueue("Ryan");
        queue.Enqueue("Kevin");

        Console.Write("Số phần tử = ");
        Console.WriteLine(queue.Count);

        queue.Clear();
        Console.Write("Số phần tử (cập nhật) = ");
        Console.WriteLine(queue.Count);
    }
}

Kết quả

Số phần tử = 8
Số phần tử (cập nhật) = 0

Các thao tác cơ bản

  • Dequeue() – lấy và xóa phần tử đầu hàng đợi.
  • Peek() – xem phần tử đầu không xóa.
  • Contains(T) – kiểm tra tồn tại (O(n)).
  • ToArray() – sao chép thành mảng.