在C#中将堆栈转换为数组
要将堆栈转换为数组,代码如下-
示例
using System; using System.Collections.Generic; public class Demo { public static void Main(){ Stack<string> stack = new Stack<string>(); stack.Push("AB"); stack.Push("CD"); stack.Push("FG"); stack.Push("KL"); Console.WriteLine("Array..."); foreach(string i in stack){ Console.WriteLine(i); } string[] strArr = stack.ToArray(); Console.WriteLine("Convert Stack to Array..."); foreach(string i in strArr){ Console.WriteLine(i); } } }
输出结果
这将产生以下输出-
Array... KL FG CD AB Convert Stack to Array... KL FG CD AB
示例
现在让我们来看另一个示例-
using System; using System.Collections.Generic; public class Demo { public static void Main(){ Stack<int> stack = new Stack<int>(); stack.Push(250); stack.Push(500); stack.Push(750); stack.Push(1000); stack.Push(1200); stack.Push(1500); Console.WriteLine("Array..."); foreach(int i in stack){ Console.WriteLine(i); } int[] intArr = stack.ToArray(); Console.WriteLine("Convert Stack to Array..."); foreach(int i in intArr){ Console.WriteLine(i); } } }
输出结果
这将产生以下输出-
Array... 1500 1200 1000 750 500 250 Convert Stack to Array... 1500 1200 1000 750 500 250