- 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
Create a Stack from a collection in C#
To create a Stack from a collection, the code is as follows −
Example
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("
Array 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 −
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("
Array 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
Advertisements