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

Array ใน C# - คู่มือครบถ้วน

Array ใน C# เป็นโครงสร้างข้อมูลที่เก็บ **ชุดข้อมูลขนาดคงที่ (Fixed-size)** ของชนิดข้อมูลเดียวกัน (Same Type) จัดเก็บในหน่วยความจำติดกัน (Contiguous Memory) เข้าถึงได้โดย **Index (0-based)**

การประกาศ Array

// Syntax: datatype[] arrayName;

// 1. Declaration + Allocation
int[] numbers = new int[10];           // 10 integers, initialized to 0
string[] names = new string[5];        // 5 strings, initialized to null

// 2. Declaration + Initialization (Array Initializer)
int[] scores = new int[] { 90, 85, 95, 88, 92 };
string[] cities = { "Bangkok", "Tokyo", "New York" };  // Short syntax

// 3. Implicitly Typed Array (var)
var primes = new[] { 2, 3, 5, 7, 11, 13 };

// 4. Multi-dimensional Arrays
int[,] matrix = new int[3, 4];           // 2D: 3 rows, 4 cols
int[,,] cube = new int[2, 3, 4];         // 3D

// 5. Jagged Arrays (Array of Arrays)
int[][] jagged = new int[3][];
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5, 6 };
jagged[2] = new int[] { 7 };

ตัวอย่างโค้ดสมบูรณ์ (1D Array)

using System;

namespace ArrayApplication {
    class MyArray {
        static void Main(string[] args) {
            int[] n = new int[10];  // Array of 10 integers
            
            // Initialize elements
            for (int i = 0; i < 10; i++) {
                n[i] = i + 100;  // 100, 101, 102, ..., 109
            }
            
            // Output each element
            for (int j = 0; j < 10; j++) {
                Console.WriteLine("Element[{0}] = {1}", j, n[j]);
            }
            
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

Array Properties และ Methods (จาก Array Class)

Member คำอธิบาย
Length จำนวน Elements ทั้งหมด (All Dimensions) - Property
Rank จำนวน Dimensions (1D=1, 2D=2, ...)
GetLength(dimension) ขนาดของ Dimension ที่ระบุ (0-based)
GetLongLength(dimension) ขนาดเป็น long (สำหรับ Array ใหญ่ > 2^31)
GetLowerBound(dimension) Lower Bound (ปกติคือ 0)
GetUpperBound(dimension) Upper Bound (Length - 1)

Multi-dimensional Array Example

// 2D Array - Matrix
int[,] matrix = {
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};

// Access: matrix[row, col]
Console.WriteLine(matrix[1, 2]);  // 6 (Row 1, Col 2)

// Iterate 2D
for (int i = 0; i < matrix.GetLength(0); i++) {  // Rows
    for (int j = 0; j < matrix.GetLength(1); j++) {  // Cols
        Console.Write(matrix[i, j] + " ");
    }
    Console.WriteLine();
}

Jagged Array Example

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

// Access: jagged[row][col]
Console.WriteLine(jagged[1][2]);  // 5

// Iterate
foreach (var row in jagged) {
    foreach (var val in row) {
        Console.Write(val + " ");
    }
    Console.WriteLine();
}

Array Methods ที่ใช้บ่อย (Static Methods)

int[] source = { 1, 2, 3, 4, 5 };
int[] dest = new int[5];

// Copy
Array.Copy(source, 0, dest, 0, 3);  // Copy 3 elements from index 0
// dest = {1, 2, 3, 0, 0}

Array.Copy(source, dest, 5);  // Copy all

// Sort
int[] unsorted = { 5, 2, 8, 1, 9 };
Array.Sort(unsorted);  // {1, 2, 5, 8, 9}

// Reverse
Array.Reverse(unsorted);  // {9, 8, 5, 2, 1}

// Binary Search (ต้อง Sorted ก่อน)
int index = Array.BinarySearch(new[] { 1, 3, 5, 7 }, 5);  // 2

// Find / FindAll / FindIndex (Predicate)
int[] nums = { 1, 2, 3, 4, 5, 6 };
int firstEven = Array.Find(nums, x => x % 2 == 0);  // 2
int[] allEven = Array.FindAll(nums, x => x % 2 == 0);  // {2, 4, 6}
int indexEven = Array.FindIndex(nums, x => x % 2 == 0);  // 1

// Resize (สร้าง Array ใหม่ขนาดใหม่)
Array.Resize(ref nums, 10);  // ขยายเป็น 10, ค่าใหม่เป็น 0

foreach vs for Loop

int[] arr = { 10, 20, 30, 40, 50 };

// for - เข้าถึง Index ได้, เร็วกว่าเล็กน้อย
for (int i = 0; i < arr.Length; i++) {
    Console.WriteLine($"[{i}] = {arr[i]}");
}

// foreach - อ่านง่าย, Read-only (ไม่ควร Modify Collection)
foreach (int val in arr) {
    Console.WriteLine(val);
}

// for แบบย้อนกลับ
for (int i = arr.Length - 1; i >= 0; i--) { ... }

Array vs List<T> - เมื่อไหร่ใช้ไหน

ด้าน Array List<T>
Size Fixed (Compile-time/Creation-time) Dynamic (Grow/Shrink)
Performance เร็วกว่าเล็กน้อย (No Bounds Check ในบางกรณี) ช้ากว่าเล็กน้อย (Bounds Check, Resize)
Memory Compact, No Overhead Overhead (Capacity > Count)
Features Basic Rich (Add, Remove, Find, Sort, LINQ)
ใช้เมื่อ Size คงที่, Performance Critical, Interop General Purpose, Dynamic Size

Best Practices

  • ใช้ Array.Empty<T>() แทน new T[0] (Shared Instance, No Allocation)
  • ใช้ Span<T> / Memory<T> สำหรับ Slicing โดยไม่ Copy
  • หลีกเลี่ยง Multi-dimensional Arrays สำหรับ Performance Critical - ใช้ Jagged หรือ 1D Array + Index Calculation
  • Initialize ด้วย Collection Expression (C# 12+): int[] arr = [1, 2, 3];