user1220052
user1220052

Reputation: 41

how to get Current index in stack using C#

I have inserted values into Stack in C# . I need values of mystack[0], mystack[1]. How to do it. I have tried methods in stack but please give me hint of code i will try it

Upvotes: 3

Views: 4616

Answers (2)

Mike Christensen
Mike Christensen

Reputation: 91628

You can use ElementAt() for this.

Stack<Int32> foo = new Stack<Int32>();
foo.Push(5); //element 1
foo.Push(1); //element 0
int val = foo.ElementAt(1); //This is 5

Since stacks are last on first out, if you want to get the first item you added to the stack, you can use:

int val = foo.ElementAt(foo.Count - 1);

Keep in mind, ElementAt is a LINQ extension method that will enumerate the stack as an array and return the desired index. For large stacks, or where performance is critical, you might want to consider using another data structure such as List<T>.

Upvotes: 4

Chris Shain
Chris Shain

Reputation: 51339

If you need the items by index, perhaps a List<T> would be a more appropriate data structure?

A stack is intended to only allow you to get the most recently inserted item. There are ways to bypass that behavior, but surely if you need the items by index this works better:

var myList = new List<Int32>();
myList.Add(100);
myList.Add(200);
myList.Add(300);
myList.Add(400);
Console.Out.WriteLine(myList[2]); // Prints "300"

Upvotes: 2

Related Questions