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

ArrayList ใน C# - คอลเลกชันไดนามิกที่ปรับขนาดได้

ArrayList คืออะไร?

ArrayList เป็นการ implement ของ interface IList ที่ปรับขนาดได้ (resizable) อยู่ใน namespace System.Collections

ลักษณะสำคัญ

  • Non-generic - เก็บข้อมูลเป็น object รองรับทุกประเภท
  • Dynamic sizing - ขยาย/หดตัวอัตโนมัติเมื่อเพิ่ม/ลบข้อมูล
  • Zero-indexed - เข้าถึงด้วยดัชนี 0 ถึง Count-1
  • Allow duplicates - อนุญาตค่าซ้ำได้

การสร้างและใช้งานพื้นฐาน

สร้าง ArrayList

ArrayList arr = new ArrayList();

เพิ่มข้อมูล

ArrayList arr1 = new ArrayList();
arr1.Add(120);
arr1.Add(160);
arr1.Add("Hello"); // สามารถเพิ่มประเภทต่างกันได้
arr1.Add(3.14);

ตัวอย่างโค้ดสมบูรณ์

using System;
using System.Collections;

public class MyClass
{
    public static void Main()
    {
        ArrayList arr1 = new ArrayList();
        arr1.Add(120);
        arr1.Add(160);
        
        ArrayList arr2 = new ArrayList();
        arr2.Add(200);
        arr2.Add(240);
        
        // รวม ArrayList อีกตัวหนึ่ง
        arr1.AddRange(arr2);
        
        // แสดงข้อมูลทั้งหมด
        for (int i = 0; i < arr1.Count; i++)
        {
            Console.WriteLine(arr1[i]);
        }
    }
}

ผลลัพธ์

120
160
200
240

เมธอดและ Properties สำคัญ

Member คำอธิบาย
Add(item) เพิ่มรายการต่อท้าย
AddRange(collection) เพิ่มหลายรายการพร้อมกัน
Insert(index, item) แทรกที่ตำแหน่งที่กำหนด
Remove(item) ลบรายการแรกที่ตรงกับค่า
RemoveAt(index) ลบที่ตำแหน่งที่กำหนด
Clear() ลบทั้งหมด
Contains(item) ตรวจสอบว่ามีรายการหรือไม่
IndexOf(item) หาตำแหน่งของรายการ
Count จำนวนรายการปัจจุบัน (Property)
Capacity ความจุปัจจุบัน (Property)
ToArray() แปลงเป็นอาร์เรย์

ArrayList vs List<T> (Generic List)

คุณสมบัติ ArrayList List<T>
Type Safety ❌ ไม่มี (boxing/unboxing) ✅ มี (compile-time checking)
Performance ช้ากว่า (boxing overhead) เร็วกว่า
Namespace System.Collections System.Collections.Generic
แนะนำสำหรับ Legacy code / COM interop โค้ดใหม่ทุกกรณี

⚠️ ข้อแนะนำ: ใช้ List<T> แทน

ใน C# สมัยใหม่ ควรใช้ List<T> แทน ArrayList เพราะ:

// ✅ แนะนำ - Type-safe, ประสิทธิภาพดีกว่า
List numbers = new List();
numbers.Add(120);
numbers.Add(160);

// ❌ ไม่แนะนำ - Legacy, boxing/unboxing overhead
ArrayList numbers = new ArrayList();
numbers.Add(120); // boxing
int n = (int)numbers[0]; // unboxing + cast

สรุป

  • ArrayList เป็น non-generic collection ที่ปรับขนาดได้
  • ใช้ Add, AddRange, Remove จัดการข้อมูล
  • เข้าถึงด้วยดัชนี 0 ถึง Count-1
  • แนะนำให้ใช้ List<T> แทนในโปรเจกต์ใหม่ เพื่อ Type Safety และ Performance