Reputation: 75
I am new to C#. Is it possible to get stack items by index like we can do in Lists in C#?
Thanks,
Upvotes: 6
Views: 17635
Reputation: 1437
It is possible to chose the element of the stack by index by calling ElementAt<T>(Int32)
or ElementAtOrDefault(Int32)
methods.
As a side note, if you're new to C#, always try to find the answers at
It's often way faster and more reliable than to look for the information on SO =)
Upvotes: 0
Reputation: 159
It is possible using ElementAt() as shown by Matias. You can also use Peek to see what is on top without popping it. You can also convert to an array and get a value by index that way.
var s = new Stack<int>();
s.Push(1);
s.Push(2);
var value = s.ToArray()[1];
You should ask yourself whether this is wise, though. All you will ever be able to do is get a snapshot of the Stack at a point in time. There are also concurrency issues to consider.
UPDATE:
Seems like Matias and I came up with very similar answers. His is a more correct answer as to what the question asks. The ToArray() approach gives you a consistent snapshot that may be a bit more stable. Subsequent calls to ElementAt() may give you different answers and may throw an exception if the stack has been popped in between calls.
Upvotes: 0
Reputation: 26281
You can achieve it using LINQ:
Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
stack.Push(3);
stack.Push(4);
int top = stack.ElementAt(0); // Returns 4
int next = stack.ElementAt(1); // Returns 3
However, if you find youself attempting to access the elements on a stack by index, then you are certainly doing something wrong, and you should redesign your solution.
Upvotes: 14