Giới thiệu
Phương thức ToArray() của Stack<T> tạo mảng mới chứa các phần tử theo thứ tự từ đỉnh (top) xuống đáy. Stack gốc không bị thay đổi.
Ví dụ 1: Stack chuyển mảng
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Stack stack = new Stack();
stack.Push("AB");
stack.Push("CD");
stack.Push("FG");
stack.Push("KL");
Console.WriteLine("Mảng (duyệt stack)...");
foreach (string i in stack)
{
Console.WriteLine(i);
}
string[] strArr = stack.ToArray();
Console.WriteLine("Chuyển Stack sang mảng...");
foreach (string i in strArr)
{
Console.WriteLine(i);
}
}
}
Kết quả
Mảng (duyệt stack)...
KL
FG
CD
AB
Chuyển Stack sang mảng...
KL
FG
CD
AB
Ví dụ 2: Stack chuyển mảng
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Stack stack = new Stack();
stack.Push(250);
stack.Push(500);
stack.Push(750);
stack.Push(1000);
stack.Push(1200);
stack.Push(1500);
Console.WriteLine("Mảng (duyệt stack)...");
foreach (int i in stack)
{
Console.WriteLine(i);
}
int[] intArr = stack.ToArray();
Console.WriteLine("Chuyển Stack sang mảng...");
foreach (int i in intArr)
{
Console.WriteLine(i);
}
}
}
Kết quả
Mảng (duyệt stack)...
1500
1200
1000
750
500
250
Chuyển Stack sang mảng...
1500
1200
1000
750
500
250
Chú ý
- Thứ tự mảng giống thứ tự duyệt
foreach(từ top xuống). - Mảng là bản sao (shallow copy), thay đổi mảng không ảnh hưởng stack.
Queue<T>cũng cóToArray()(thứ tự FIFO).