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

หาความยาว Jagged Array ด้วย Property Length ใน C#

ภาพรวม

Jagged Array (T[][]) เป็น Array ของ Arrays ใช้ Length หาจำนวนแถว (Rows) และ Rank จะเป็น 1 เสมอ

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


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 (number of rows): {jagged.Length}");
        Console.WriteLine($"Rank (dimensions): {jagged.Rank}");
        Console.WriteLine($"Lower Bound (dim 0): {jagged.GetLowerBound(0)}");
        Console.WriteLine($"Upper Bound (dim 0): {jagged.GetUpperBound(0)}");

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

ผลลัพธ์


Length (number of 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

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

// Total elements
int total = jagged.Sum(row => row.Length);
Console.WriteLine($"Total elements: {total}"); // 10

Iteration Patterns


// 1. Nested foreach (แนะนำ)
foreach (var row in jagged) {
    foreach (var item in row) {
        Console.Write($"{item} ");
    }
    Console.WriteLine();
}

// 2. For loops (ต้องการ index)
for (int i = 0; i < jagged.Length; i++) {
    for (int j = 0; j < jagged[i].Length; j++) {
        Console.Write($"{jagged[i][j]} ");
    }
    Console.WriteLine();
}

// 3. LINQ SelectMany (Flatten)
var allElements = jagged.SelectMany(row => row).ToArray();

เปรียบเทียบ: Jagged vs Multidimensional

คุณสมบัติJagged int[][]Multidimensional int[,]
Rank12+
Row LengthsVariableFixed
MemoryNon-contiguousContiguous
Accessarr[i][j]arr[i,j]
CLR Optimizationดีกว่า (no bounds check ทุกมิติ)Bounds check ทุกมิติ