This post will discuss how to iterate over a stack in C#.

1. Using while loop

A simple solution is to remove and process the stack’s items using the standard pop function, one at a time, until the stack gets empty. The problem with this solution is that it pops items from the stack container and then prints them, resulting in the stack becoming empty at the end. This can be avoided by creating a copy of the stack object and processing the copy. This way the original stack remains untouched, but its copy becomes empty.

Download  Run Code

Output:

5
4
3
2
1

2. Using foreach loop

A better solution is to iterate over the stack using a foreach loop. The foreach statement provides a simple, clean way to iterate through the elements of a container. The following example shows its usage by enumerating over the stack in LIFO order without disturbing its contents.

Download  Run Code

Output:

5
4
3
2
1

That’s all about iterating over a stack in C#.