Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Duyệt mảng 2 chiều trong C#


Giới thiệu

Mảng 2 chiều (rectangular array) trong C# khai báo bằng type[,]. Duyệt qua các phần tử dùng lồng vòng lặp for với GetUpperBound(dimension) để lấy chỉ số lớn nhất của mỗi chiều.

Ví dụ cơ bản

string[,] array = new string[3, 3];
array[0, 0] = "One";   array[0, 1] = "Two";   array[0, 2] = "Three";
array[1, 0] = "Four";  array[1, 1] = "Five";  array[1, 2] = "Six";
array[2, 0] = "Seven"; array[2, 1] = "Eight"; array[2, 2] = "Nine";

int uBound0 = array.GetUpperBound(0); // 2 (chiều 0: hàng)
int uBound1 = array.GetUpperBound(1); // 2 (chiều 1: cột)

Ví dụ hoàn chỉnh

using System;

public class Demo
{
    public static void Main()
    {
        string[,] array = new string[3, 3];
        array[0, 0] = "One";   array[0, 1] = "Two";   array[0, 2] = "Three";
        array[1, 0] = "Four";  array[1, 1] = "Five";  array[1, 2] = "Six";
        array[2, 0] = "Seven"; array[2, 1] = "Eight"; array[2, 2] = "Nine";

        int uBound0 = array.GetUpperBound(0);
        int uBound1 = array.GetUpperBound(1);

        for (int i = 0; i <= uBound0; i++)
        {
            for (int j = 0; j <= uBound1; j++)
            {
                string res = array[i, j];
                Console.WriteLine(res);
            }
        }
    }
}

Kết quả

One
Two
Three
Four
Five
Six
Seven
Eight
Nine

Các cách duyệt khác

1. Dùng Length và Rank

int rows = array.GetLength(0); // 3
int cols = array.GetLength(1); // 3
for (int i = 0; i < rows; i++)
    for (int j = 0; j < cols; j++)
        Console.WriteLine(array[i, j]);

2. Duyệt với foreach (không có chỉ số)

foreach (string s in array)
    Console.WriteLine(s);

3. Mảng răng cưa (Jagged Array) - type[][]

string[][] jagged = new string[3][];
jagged[0] = new[] { "One", "Two" };
jagged[1] = new[] { "Three", "Four", "Five" };
jagged[2] = new[] { "Six" };

foreach (var row in jagged)
    foreach (var item in row)
        Console.WriteLine(item);

Lưu ý

  • GetUpperBound(0) = chiều đầu tiên (hàng), GetUpperBound(1) = chiều thứ hai (cột).
  • Chỉ số từ 0 đến UpperBound (inclusive).
  • Mảng 2 chiều lưu liên tục trong bộ nhớ (cache-friendly).
  • Mảng răng cưa (jagged) linh hoạt hơn nhưng truy cập chậm hơn do dereference nhiều cấp.