Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

หาความยาวและ Rank ของ Jagged Array ใน C#

ภาพรวม

Jagged Array (int[][]) คือ Array ของ Arrays - แต่ละแถวมีความยาวต่างกันได้ Rank = 1 เสมอ (เพราะเป็น 1D array ของ arrays)

โค้ดตัวอย่าง


using System;

public class Program {
    public static void Main() {
        int[][] jagged = new int[][] {
            new int[] { 0, 0 },
            new int[] { 1, 2 },
            new int[] { 2, 4 },
            new int[] { 3, 6 },
            new int[] { 4, 8 }
        };

        Console.WriteLine($"Length (rows): {jagged.Length}");           // 5
        Console.WriteLine($"Rank (dimensions): {jagged.Rank}");         // 1
        Console.WriteLine($"Lower Bound (dim 0): {jagged.GetLowerBound(0)}"); // 0
        Console.WriteLine($"Upper Bound (dim 0): {jagged.GetUpperBound(0)}"); // 4

        // ความยาวแต่ละแถว
        Console.WriteLine("\\nRow lengths:");
        for (int i = 0; i < jagged.Length; i++) {
            Console.WriteLine($"Row {i}: Length = {jagged[i].Length}");
        }

        // Total elements
        int totalElements = 0;
        foreach (var row in jagged) totalElements += row.Length;
        Console.WriteLine($"\\nTotal elements: {totalElements}");
    }
}

ผลลัพธ์


Length (rows): 5
Rank (dimensions): 1
Lower Bound (dim 0): 0
Upper Bound (dim 0): 4

Row lengths:
Row 0: Length = 2
Row 1: Length = 2
Row 2: Length = 2
Row 3: Length = 2
Row 4: Length = 2

Total elements: 10

Jagged Array ที่มีความยาวแถวต่างกัน


int[][] jagged = new int[][] {
    new int[] { 1, 2, 3 },      // Length 3
    new int[] { 4, 5 },         // Length 2
    new int[] { 6, 7, 8, 9 },   // Length 4
    new int[] { 10 }            // Length 1
};

Console.WriteLine($"Rows: {jagged.Length}"); // 4
Console.WriteLine($"Rank: {jagged.Rank}");   // 1

for (int i = 0; i < jagged.Length; i++) {
    Console.WriteLine($"Row {i}: {string.Join(", ", jagged[i])}");
}

ผลลัพธ์


Rows: 4
Rank: 1
Row 0: 1, 2, 3
Row 1: 4, 5
Row 2: 6, 7, 8, 9
Row 3: 10

เปรียบเทียบ: 2D Array (Rectangular) vs Jagged Array

คุณสมบัติ2D Array int[,]Jagged Array int[][]
Rank21
Memory LayoutContiguous blockArray of references to arrays
Row LengthsFixed (all same)Variable
Access Syntaxarr[i, j]arr[i][j]
PerformanceCache-friendlyExtra indirection
CLS Compliantใช่ใช่