Create a Queue from another collection in C#?

CsharpServer Side ProgrammingProgramming

To create a Queue from another collection, the code is as follows −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Queue<string> queue = new Queue<string>();
      queue.Enqueue("One");
      queue.Enqueue("Two");
      queue.Enqueue("Three");
      Console.WriteLine("Queue elements...");
      foreach(string str in queue) {
         Console.WriteLine(str);
      }
      Console.WriteLine("\nArray elements...");
      Queue<string> arr = new Queue<string>(queue.ToArray());
      foreach(string str in arr) {
         Console.WriteLine(str);
      }
   }
}

Output

This will produce the following output −

Queue elements...
One
Two
Three

Array elements...
One
Two
Three

Let us now see another example −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Queue<int> queue = new Queue<int>();
      queue.Enqueue(100);
      queue.Enqueue(200);
      queue.Enqueue(300);
      queue.Enqueue(400);
      queue.Enqueue(500);
      queue.Enqueue(600);
      queue.Enqueue(700);
      queue.Enqueue(800);
      queue.Enqueue(900);
      queue.Enqueue(1000);
      Console.WriteLine("Queue elements...");
      foreach(int val in queue) {
         Console.WriteLine(val);
      }
      Console.WriteLine("\nArray elements...");
      Queue<int> arr = new Queue<int>(queue.ToArray());
      foreach(int val in arr) {
         Console.WriteLine(val);
      }
   }
}

Output

This will produce the following output −

Queue elements...
100
200
300
400
500
600
700
800
900
1000
Array elements...
100
200
300
400
500
600
700
800
900
1000
raja
Published on 16-Dec-2019 07:05:46
Advertisements