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

ความแตกต่างระหว่าง List Collection และ Array ใน C#

Array (อาเรย์)

เก็บข้อมูลชนิดเดียวกัน ขนาดคงที่ (Fixed Size) ต้องระบุขนาดตอนสร้าง

การประกาศ Array

// ประกาศพร้อมขนาด
int[] arr = new int[5];

// ประกาศพร้อมค่าเริ่มต้น
int[] arr2 = new int[5] { 4, 8, 5, 2, 9 };
int[] arr3 = { 4, 8, 5, 2, 9 }; // Shorthand

// หลายมิติ
int[,] matrix = new int[3, 3];

List<T> (Generic List)

Collection แบบ Dynamic Size เพิ่ม/ลบได้ ตัว Generic รองรับ Type ใดๆ

การประกาศ List

using System.Collections.Generic;

// ว่าง
List list = new List();

// พร้อม Capacity เริ่มต้น
List list2 = new List(100);

// พร้อมค่าเริ่มต้น (Collection Initializer)
List list3 = new List { "One", "Two", "Three" };

การเพิ่ม/ลบข้อมูลใน List

List list = new List();

list.Add("One");           // เพิ่มท้าย
list.AddRange(new[] { "Two", "Three" }); // เพิ่มหลายตัว
list.Insert(0, "Zero");    // แทรกที่ Index 0

list.Remove("Two");        // ลบค่าแรกที่เจอ
list.RemoveAt(0);          // ลบที่ Index
list.RemoveAll(x => x.StartsWith("T")); // ลบทุกตัวที่ match
list.Clear();              // ลบทั้งหมด

ตารางเปรียบเทียบครบถ้วน

คุณสมบัติ Array List<T>
ขนาด (Size) Fixed (กำหนดตอนสร้าง) Dynamic (เพิ่ม/ลบได้)
Syntax T[] List<T>
Namespace System (Built-in) System.Collections.Generic
เพิ่มข้อมูล ไม่ได้ (ต้องสร้างใหม่) Add(), Insert(), AddRange()
ลบข้อมูล ไม่ได้ Remove(), RemoveAt(), Clear()
เข้าถึง Index arr[i] list[i]
Count/Length arr.Length list.Count
Capacity N/A (เท่ากับ Length) list.Capacity (Internal Buffer)
LINQ Support ✅ (Implements IEnumerable) ✅ (Implements IEnumerable)
Performance (Access) เร็วที่สุด (Direct Memory) เร็ว (Bounds Check + 1 Indirection)
Memory Overhead ต่ำสุด มี Overhead (Object Header, Capacity Buffer)
Thread Safety ไม่ปลอดภัย ไม่ปลอดภัย (ใช้ ConcurrentBag/ImmutableList)

การแปลงระหว่าง Array และ List

// Array -> List
int[] arr = { 1, 2, 3 };
List list = new List(arr); // Constructor
// หรือ
List list2 = arr.ToList(); // LINQ

// List -> Array
List list = new List { 1, 2, 3 };
int[] arr2 = list.ToArray(); // สร้าง Array ใหม่ขนาดพอดี
// หรือ
int[] arr3 = new int[list.Count];
list.CopyTo(arr3); // คัดลอกไป Array ที่มีอยู่

เมื่อไหร่ควรใช้ Array?

  • ขนาดทราบล่วงหน้าและไม่เปลี่ยน
  • Performance Critical (Hot Path, Game Loop, Math)
  • Interop กับ Native Code / APIs
  • Multi-dimensional Data (Matrix)
  • Struct Arrays (Value Type - No Boxing)

เมื่อไหร่ควรใช้ List<T>?

  • ขนาดไม่ทราบล่วงหน้า / เปลี่ยนแปลงบ่อย
  • ต้องการ Add/Remove/Insert/Search
  • General Purpose Collection (Default Choice)
  • ทำงานกับ LINQ บ่อย

Performance Tip

// ถ้ารู้ขนาดประมาณ - Reserve Capacity เพื่อหลีกเลี่ยง Resize
List list = new List(10000); // Capacity = 10000

// ตรวจสอบ Capacity
Console.WriteLine(list.Capacity); // Internal Buffer Size
Console.WriteLine(list.Count);    // Actual Elements