C# Queue

C# collections

In C#, Queue is a First In First Out (FIFO) data structure.

Queue belongs to the System.Collections or System.Collections.Generic namespaces, which provide non-generic and generic implementations, respectively. Queue is suitable for scenarios where data needs to be processed in the order it was enqueued.

Queue represents afirst-in, first-outA collection of objects. When you need first-in, first-out access to items, use a queue. When you add an item to the list, it is calledEnqueue, and when you remove an item from the list, it is calledDequeue。

Features

  • first-in, first-out: the element that was added to the queue earliest is removed first.
  • Dynamic size: the capacity of the queue is dynamically adjusted as needed.
  • Generic support: throughQueue<T>can store strongly-typed elements.
  • Thread Safety:Queueis not thread-safe by itself, but you can useConcurrentQueue<T>Implement thread safety.

Methods and properties of the Queue class

The table below listsQueueSome common uses of the classProperty:

Attribute NameTypeDescription
CountintGets the number of elements in the queue.
SyncRootobjectto obtain an object for synchronizing access to the queue (non-generic).
IsSynchronizedboolIndicates whether access to the queue is synchronized (thread-safe, alwaysfalse)。

The table below listsQueueSome common uses of the classMethods:

Method NameReturn TypeDescription
Element operations
Enqueue(object item)voidAdds an element to the end of the queue.
Dequeue()objectRemoves and returns the element at the beginning of the queue.
Peek()objectReturns the element at the beginning of the queue without removing it.
Clear()voidRemoves all elements from the queue.
Check and copy
Contains(object item)boolDetermines whether an element exists in the queue.
ToArray()object[]Copy the elements in the queue to a new array.
Clone()objectCreates a shallow copy of the current queue.
CopyTo(Array array, int index)voidCopies the elements in the queue to an existing array, starting at the specified index.
Enumerator support
GetEnumerator()IEnumeratorReturns an enumerator that iterates through the elements in the queue.
Thread Safety
Synchronized(Queue queue)QueueReturns a thread-safe queue wrapper.

Example

The following example demonstrates the use of Queue:

Example 1

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        Queue queue = new Queue();

        // Add elements
        queue.Enqueue("First");
        queue.Enqueue("Second");
        queue.Enqueue("Third");

        // Peek at front
        Console.WriteLine($"Peek: {queue.Peek()}"); // Output: First

        // Remove element
        Console.WriteLine($"Dequeue: {queue.Dequeue()}"); // Output: First

        // Remaining elements
        foreach (var item in queue)
        {
            Console.WriteLine(item); // Output: Second, Third
        }

        // Check contains
        Console.WriteLine($"Contains 'Second': {queue.Contains("Second")}"); // output: True

        // Convert to array
        object[] array = queue.ToArray();
        Console.WriteLine($"Array Length: {array.Length}"); // Output: 2
    }
}

Example 2

using System;
using System.Collections;

namespace CollectionsApplication
{
   class Program
   {
      static void Main(string[] args)
      {
         Queue q = new Queue();

         q.Enqueue('A');
         q.Enqueue('M');
         q.Enqueue('G');
         q.Enqueue('W');
         
         Console.WriteLine("Current queue: ");
         foreach (char c in q)
            Console.Write(c + " ");
         Console.WriteLine();
         q.Enqueue('V');
         q.Enqueue('H');
         Console.WriteLine("Current queue: ");        
         foreach (char c in q)
            Console.Write(c + " ");
         Console.WriteLine();
         Console.WriteLine("Removing some values ");
         char ch = (char)q.Dequeue();
         Console.WriteLine("The removed value: {0}", ch);
         ch = (char)q.Dequeue();
         Console.WriteLine("The removed value: {0}", ch);
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces the following results:

Current queue: 
A M G W 
Current queue: 
A M G W V H 
Removing values
The removed value: A
The removed value: M

C# collections

other extensions