Create a Stack from a collection in C#

CsharpServer Side ProgrammingProgramming

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

Example

 Live Demo

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

Output

This will produce the following output−

Stack elements...
1000
900
800
700
600
500
400
300
200
100

Array elements...
100
200
300
400
500
600
700
800
900
1000

Example

Let us now see another example −

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Stack<string> stack = new Stack<string>();
      stack.Push("Katie");
      stack.Push("Andy");
      stack.Push("Ariane");
      stack.Push("Justin");
      Console.WriteLine("Stack elements...");
      foreach(string val in stack){
         Console.WriteLine(val);
      }
      Console.WriteLine("\nArray elements...");
      Stack<string> arr = new Stack<string>(stack.ToArray());
      foreach(string val in arr){
         Console.WriteLine(val);
      }
   }
}

Output

This will produce the following output −

Stack elements...
Justin
Ariane
Andy
Katie

Array elements... 
Katie 
Andy 
Ariane 
Justin
raja
Published on 05-Dec-2019 06:14:49
Advertisements