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

Index-based I/O ArrayList Collection ใน C#

ArrayList Class

ArrayList เป็น Non-Generic Collection ที่เก็บ Object ใดๆ ได้ ขนาด Dynamic (เพิ่ม/ลบได้) เข้าถึงแบบ Index-Based เหมือน Array - อยู่ใน System.Collections

⚠️ หมายเหตุ: ใน C# สมัยใหม่ ควรใช้ List<T> แทน ArrayList เพื่อ Type Safety และ Performance (No Boxing/Unboxing)

Properties หลัก

Property คำอธิบาย
Capacity จำนวนสมาชิกที่จัดเก็บได้ (Internal Buffer) - เพิ่มอัตโนมัติ
Count จำนวนสมาชิกจริงในปัจจุบัน
IsFixedSize เป็น Fixed Size หรือไม่ (ArrayList = false)
IsReadOnly เป็น Read-Only หรือไม่
Item[int index] Get/Set สมาชิกที่ Index (Indexer)

Methods หลัก

Method คำอธิบาย
Add(object) เพิ่มสมาชิกท้าย - คืน Index
AddRange(ICollection) เพิ่มหลายสมาชิก
Insert(index, object) แทรกที่ Index
Remove(object) ลบสมาชิกแรกที่เจอ
RemoveAt(index) ลบที่ Index
RemoveRange(index, count) ลบช่วง
Clear() ลบทั้งหมด
Contains(object) ตรวจสอบว่ามีสมาชิกหรือไม่
IndexOf(object) หา Index แรกที่เจอ
ToArray() แปลงเป็น Array
Sort() เรียงลำดับ (IComparable)
Reverse() กลับลำดับ

ตัวอย่างการใช้งาน

using System;
using System.Collections;

namespace Demo {
    class Program {
        static void Main(string[] args) {
            ArrayList list = new ArrayList();
            
            // เพิ่มข้อมูล (Boxing เกิดขึ้นกับ Value Types)
            list.Add(45);      // int -> object (Boxing)
            list.Add(53);
            list.Add(12);
            list.Add(88);
            list.Add("Hello"); // สามารถผสม Type ได้!
            list.Add(3.14);
            
            Console.WriteLine("Count: " + list.Count);    // 6
            Console.WriteLine("Capacity: " + list.Capacity); // 8 (Default 4 -> Double)
            
            // เข้าถึงด้วย Index (ต้อง Cast/Unboxing)
            int first = (int)list[0]; // Unboxing
            string str = (string)list[4];
            
            Console.WriteLine("First: " + first);
            Console.WriteLine("String: " + str);
            
            // วนลูป
            Console.WriteLine("\nAll items:");
            foreach (object item in list) {
                Console.WriteLine($"{item.GetType().Name}: {item}");
            }
            
            // เรียงลำดับ (ต้องเป็น Type เดียวกันและ IComparable)
            ArrayList numbers = new ArrayList { 5, 2, 8, 1, 9 };
            numbers.Sort();
            Console.WriteLine("\nSorted: " + string.Join(", ", numbers.ToArray()));
        }
    }
}

ผลลัพธ์

Count: 6
Capacity: 8
First: 45
String: Hello

All items:
Int32: 45
Int32: 53
Int32: 12
Int32: 88
String: Hello
Double: 3.14

Sorted: 1, 2, 5, 8, 9

ArrayList vs List<T> - เหตุผลที่ควรใช้ List<T>

ด้านเปรียบเทียบ ArrayList List<T>
Type Safety ❌ Object (Boxing/Unboxing) ✅ Strongly Typed
Performance (Value Types) ช้า (Boxing Overhead) เร็ว (No Boxing)
Compile-time Checking ไม่มี มี
IntelliSense จำกัด เต็มรูปแบบ
Memory มากกว่า (Object Header ต่อ Item) น้อยกว่า

เมื่อไหร่ต้องใช้ ArrayList (Legacy)

  • รหัสเก่า (Legacy Code) .NET Framework 1.0/1.1
  • COM Interop ที่ต้องการ IList แบบ Non-Generic
  • การผสม Type จริงๆ (Rare - ใช้ List<object> แทนได้)

Best Practice: Migration to List<T>

// เก่า
ArrayList oldList = new ArrayList();
oldList.Add(1);
oldList.Add("two");

// ใหม่ - Option 1: List (ยังผสม Type ได้)
List newList = new List();
newList.Add(1);
newList.Add("two");

// ใหม่ - Option 2: แยก Type (แนะนำ)
List intList = new List { 1, 2, 3 };
List strList = new List { "one", "two" };