Mega Code Archive

 
Categories / C# Book / 03 Collections
 

0357 Generic Queue and Non-generic Queue

Queue<T> and Queue are first-in first-out (FIFO) data structures, providing methods to Enqueue (add an item to the tail of the queue) and Dequeue (retrieve and remove the item at the head of the queue). A Peek method is also provided to return the element at the head of the queue without removing it, and a Count property. The generic version of Queue has the following methods: public class Queue<T> : IEnumerable<T>, ICollection, IEnumerable { public Queue(); public Queue (IEnumerable<T> collection); // Copies existing elements public Queue (int capacity); // To lessen auto-resizing public void Clear(); public bool Contains (T item); public void CopyTo (T[] array, int arrayIndex); public int Count { get; } public T Dequeue(); public void Enqueue (T item); public Enumerator<T> GetEnumerator(); // To support foreach public T Peek(); public T[] ToArray(); public void TrimExcess(); } The following is an example of using Queue<int>: using System; using System.Collections; using System.Collections.Generic; using System.Linq; class Sample { public static void Main() { var q = new Queue<int>(); q.Enqueue(10); q.Enqueue(20); int[] data = q.ToArray(); // Exports to an array Console.WriteLine (q.Count); Console.WriteLine (q.Peek()); Console.WriteLine(q.Dequeue()); Console.WriteLine (q.Dequeue()); Console.WriteLine(q.Dequeue()); } } The output: 2 10 10 20 Unhandled Exception: System.InvalidOperationException: Queue empty. at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resour ce) at System.Collections.Generic.Queue`1.Dequeue() at Sample.Main() in c:\g\Program.cs:line 18