在C#中,遍歷二維數組的方法有以下幾種:
int[,] array = new int[3, 4];
// 使用外層循環遍歷行,內層循環遍歷列
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
Console.Write(array[i, j] + " ");
}
Console.WriteLine();
}
int[,] array = new int[3, 4];
// 獲取數組的行數和列數
int rows = array.GetLength(0);
int cols = array.GetLength(1);
// 使用foreach循環遍歷數組元素
foreach (int element in array)
{
Console.Write(element + " ");
// 當遍歷到每行的最后一個元素時換行
if ((Array.IndexOf(array, element) + 1) % cols == 0)
{
Console.WriteLine();
}
}
using System.Linq;
int[,] array = new int[3, 4];
// 使用LINQ查詢遍歷數組元素
var query = from int element in array select element;
foreach (int element in query)
{
Console.Write(element + " ");
}
這些方法都可以用于遍歷二維數組。你可以根據自己的需求和編程風格選擇合適的方法。