How to Convert a Stack to an Array Without Losing The LIFO Order

29-05-2012

The index of elements in a stack increments. i.e. the latest item would have
the largest index (which is equal to Stack.Length – 1).

But when you use Stack.ToArray() method it returns items in the other way. So the
first item in the array is the last item you put in the stack. This is good in many ways but you may want to stick to the order of the stack.

Following example illustrates this (the normal behaviour):

            Stack<string> teststack = new Stack<string>();
            teststack.Push("first");
            teststack.Push("second");
            teststack.Push("third");

            string[] strings = teststack.ToArray();
            for (int i = 0; i < strings.Length; i++)
            {
                Console.WriteLine(i.ToString() + " - " + strings[i]);
            }

            Console.ReadKey();
// Output
0 -  third
1 - second
2 - first

If you want to retain the LIFO order simply call Stack.Reverse() method
before calling the ToArray()

            Stack<string> teststack = new Stack<string>();
            teststack.Push("first");
            teststack.Push("second");
            teststack.Push("third");

            string[] strings = teststack.Reverse().ToArray();
            for (int i = 0; i < strings.Length; i++)
            {
                Console.WriteLine(i.ToString() + " - " + strings[i]);
            }

            Console.ReadKey();
// Output
0 -  first
1 - second
2 - third

Menol

3 thoughts on “How to Convert a Stack to an Array Without Losing The LIFO Order

  1. As my idea, to get the items with the LIFO order, you should not modify the stack. You have to access the items in the reverse order without affecting your source object (as a best practice). The solution is to write a reverse “for” loop instead of common forward “for” loop. The snippet for the reverse for loop can get by typing “forr” in VS editor and hit “Tab” twice. This will reduce the workload and the code lines as well. Good luck!

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: