Ignora collegamentiHome / Blog

Blog


How to use Queue in C#

This simple example shows how to use Queue in C#.

using System;
using System.Collections;

class QueueTest
{  
    public static void Main()  
    {  
        // Create a queue of Person,     
        // Simple collection FIFO (First-In, First-Out) objects of type Person
        Queue personQueue = new Queue();
       
        //
        personQueue.Enqueue(new Person("Barbara", "Denver", 34));
        personQueue.Enqueue(new Person("Sofia", "Brucks", 32));
        personQueue.Enqueue(new Person("Elena", "Silver", 31));
        personQueue.Enqueue(new Person("Asia", "Solis", 38));
        personQueue.Enqueue(new Person("Paris", "Jordan", 25));
       
        // Prints some informations of the Queue
        Console.WriteLine();
        Console.WriteLine("The Queue contains " + personQueue.Count + " elements" );
        Console.WriteLine("The first element of the Queue is: " + personQueue.Peek());

        // Prints the contents of the Queue
        Console.WriteLine();
        Console.WriteLine("Queue contains the following elements:");
        foreach(Person p in personQueue)
        {
            Console.WriteLine(p.ToString());
        }
       
        // Pop some elements from the Queue
        personQueue.Dequeue();
        personQueue.Dequeue();
       
        // Prints the contents of the Queue
        Console.WriteLine();
        Console.WriteLine("After 2 Dequeue(), Queue contains the following elements:");
        foreach(Person p in personQueue)
        {
            Console.WriteLine(p.ToString());
        }
    }
}

/// <summary>
/// A typical sample class for objects of type Person
/// This class implements the interface IComparable
/// </summary>
class Person : IComparable
{
    string name;
    string surname;
    byte age;
   
    public Person()
    {}
   
    public Person(string n, string s, byte a)
    {
    name = n;
    surname = s;
    age = a;
    }
   
    public override string ToString()
    {
        return name+ ", " + surname + ", (" + age + ")";
    }
   
    public int CompareTo(object obj)
    {
        if(obj is Person) {
            Person p = (Person) obj;
            return age.CompareTo(p.age);
        }
        throw new ArgumentException("object is not a Person");   
    }
}

 

This is the output of the program:


The Queue contains 5 elements
The first element of the Queue is: Barbara, Denver, (34)

Queue contains the following elements:
Barbara, Denver, (34)
Sofia, Brucks, (32)
Elena, Silver, (31)
Asia, Solis, (38)
Paris, Jordan, (25)

After 2 Dequeue(), Queue contains the following elements:
Elena, Silver, (31)
Asia, Solis, (38)
Paris, Jordan, (25)



Category: C#