Phương thức Array.Reverse() đảo ngược thứ tự các phần tử trong toàn bộ mảng một chiều.
Ví dụ
using System;
namespace Demo
{
class MyArray
{
static void Main(string[] args)
{
int[] list = { 29, 15, 30, 98 };
int[] temp = (int[])list.Clone(); // Sao chép để giữ nguyên mảng gốc
Console.Write("Mảng gốc: ");
foreach (int i in list)
Console.Write(i + " ");
Console.WriteLine();
// Đảo ngược mảng
Array.Reverse(temp);
Console.Write("Mảng đảo ngược: ");
foreach (int i in temp)
Console.Write(i + " ");
Console.ReadKey();
}
}
}
Kết quả
Mảng gốc: 29 15 30 98 Mảng đảo ngược: 98 30 15 29
Overloads
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
Array.Reverse(arr, 2, 4); // Đảo 4 phần tử từ index 2
// Kết quả: 1 2 6 5 4 3 7 8