- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the Queue class in C#?
To represent a first-in first-out collection of objects in C#, use the Queue class. When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque.
Some of the methods of the Queue class include.
Sr.No | Method & Description |
---|---|
1 | public virtual void Clear(); Removes all elements from the Queue. |
2 | public virtual bool Contains(object obj); Determines whether an element is in the Queue. |
3 | public virtual object Dequeue(); Removes and returns the object at the beginning of the Queue. |
4 | public virtual void Enqueue(object obj); Adds an object to the end of the Queue. |
5 | public virtual object[] ToArray(); Copies the Queue to a new array. |
Let us see how to work with enqueue and deque in C# that comes under the queue class.
Example
using System; using System.Collections; namespace Demo { class Program { static void Main(string[] args) { Queue q = new Queue(); q.Enqueue('A'); q.Enqueue('B'); q.Enqueue('C'); q.Enqueue('D'); Console.WriteLine("Current queue: "); foreach (char c in q) Console.Write(c + " "); Console.WriteLine(); q.Enqueue('E'); q.Enqueue('F'); q.Enqueue('G'); 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("Value removed: {0}", ch); ch = (char)q.Dequeue(); Console.WriteLine("Value removed: {0}", ch); Console.ReadKey(); } } }
Output
Current queue: A B C D Current queue: A B C D E F G H Removing some values Value removed: A Value removed: B
Above, using enqueue the elements are added.
Queue q = new Queue(); q.Enqueue('A'); q.Enqueue('B'); q.Enqueue('C'); q.Enqueue('D');
The elements are deleted using dequeue.
char ch = (char)q.Dequeue(); Console.WriteLine("Value removed: {0}", ch);
Advertisements