![]() | ![]() |
To access elements from a Queue, you can use Peek() or Dequeue() methods. The Peek() method returns the first element from the Queue, whereas Dequeue() removes and returns the first item from the Queue. Take a look at the following example.
––––––––
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace MyProgram
{
class Program
{
static void Main(string[] args)
{
Queue newqueue = new Queue();
newqueue.Enqueue(true);
newqueue.Enqueue(10);
newqueue.Enqueue("hello");
newqueue.Enqueue(1.65);
Console.WriteLine(newqueue.Peek());
Console.WriteLine(newqueue.Dequeue());
Console.WriteLine(newqueue.Count);
Console.ReadLine();
}
}
}
In the script above, we use the Peek() method to return the first element which will be “true”. Next, we use the Dequeue() method to return the first element which will again return “true” but it will remove the first element from the list as well. Next, we count the number of elements in our Queue which should be 3 now since one of the items have been removed. The output of the script above looks like this:
In addition to Peek() and Dequeue() method to access the items in a Queue, you can use a foreach loop to iterate through each item in the Queue. You will need to convert the Queue into an array using the ToArray() method as shown below:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace MyProgram
{
class Program
{
static void Main(string[] args)
{
Queue newqueue = new Queue();
newqueue.Enqueue(true);
newqueue.Enqueue(10);
newqueue.Enqueue("hello");
newqueue.Enqueue(1.65);
foreach (var item in newqueue.ToArray())
Console.WriteLine(item);
Console.ReadLine();
}
}
}
In the script above, we iterate through all the items in the Queue “newqueue”. The output of the script above, looks like this: