C# 堆栈 - ToArray() 方法

C# 堆栈 ToArray() 方法用于将堆栈复制到新数组中。元素按照后进先出 (LIFO) 的顺序复制到数组中,类似于 pop 方法返回元素的顺序。此方法的复杂度为 O(n),其中 n 是元素数量或计数。

语法

以下是 C# 堆栈 ToArray() 方法的语法 -

public virtual object?[] ToArray ();

参数

此方法不接受任何参数。

返回值

此方法返回一个包含 Stack 元素副本的新数组。

示例 1:将 Stack 复制到数组

以下是演示 ToArray() 方法用法的基本示例 -

using System;
using System.Collections.Generic;
class Program {
   static void Main() {
      Stack<string> stack = new Stack<string>();
   
      stack.Push("First");
      stack.Push("Second");
      stack.Push("Third");
      stack.Push("Fourth");
   
      // 将堆栈转换为数组
      string[] array = stack.ToArray();
   
      // 显示数组元素
      Console.WriteLine("Array Elements:");
      foreach (var item in array) {
         Console.WriteLine(item);
      }
   }
}

输出

以下是输出 -

Array Elements:
Fourth
Third
Second
First

示例 2:处理堆栈数据

本示例演示如何将堆栈转换为数组,然后在不修改原始堆栈的情况下对数组执行操作 -

using System;
using System.Collections.Generic;
class Program {
   static void Main() {
      Stack<int> numbers = new Stack<int>();
   
      numbers.Push(10);
      numbers.Push(20);
      numbers.Push(30);
      numbers.Push(40);
      numbers.Push(50);
   
      // 将堆栈转换为数组
      int[] numArray = numbers.ToArray();
   
      // 显示数组元素
      Console.WriteLine("Array Elements (Converted from Stack):");
      foreach (var num in numArray) {
         Console.Write(num + " ");
      }
   
      // 查找数组中元素的总和
      int sum = 0;
      foreach (var num in numArray) {
         sum += num;
      }
      Console.WriteLine("
Sum of Array Elements: " + sum);
   }
}

输出

以下是输出 -

Array Elements (Converted from Stack):
50 40 30 20 10 

Sum of Array Elements: 150

示例 3:反转句子

此示例演示如何使用堆栈反转句子中的单词,然后将堆栈转换为数组 -

using System;
using System.Collections.Generic;

class Example3 {
   static void Main() {
      	string sentence = "C# Stack ToArray Example";
      	Stack<string> wordsStack = new Stack<string>();

        // 将句子拆分成单词并将其压入堆栈
        foreach (string word in sentence.Split(' '))
        {
        wordsStack.Push(word);
        }
        
        // 将堆栈转换为数组
        string[] reversedWords = wordsStack.ToArray();
        
        // 显示反转的句子
      	Console.WriteLine("Reversed Sentence: " + string.Join(" ", reversedWords));
   }
}

输出

以下是输出 -

Reversed Sentence: Example ToArray Stack C#

csharp_stack.html