คลาส ArrayList ใน C#
ArrayList เป็นคอลเลกชันแบบ Dynamic Array (ขนาดเปลี่ยนแปลงได้) เก็บข้อมูลชนิด object ได้ทุกชนิด อยู่ใน System.Collections Note: Legacy Class - ควรใช้ List<T> แทน
เมธอดสำคัญของ ArrayList
| # | เมธอด | คำอธิบาย |
| 1 | Add(object) | เพิ่มอ็อบเจกต์ท้ายสุด |
| 2 | AddRange(ICollection) | เพิ่มหลายรายการจากคอลเลกชันอื่น |
| 3 | Clear() | ล้างข้อมูลทั้งหมด |
| 4 | Contains(object) | ตรวจสอบว่ามีข้อมูลหรือไม่ |
| 5 | GetRange(index, count) | ดึง Sub-ArrayList |
| 6 | IndexOf(object) | หา Index แรกที่เจอ |
| 7 | Insert(index, object) | แทรกที่ Index ที่กำหนด |
| 8 | InsertRange(index, ICollection) | แทรกหลายรายการที่ Index |
| 9 | Remove(object) | ลบรายการแรกที่เจอ |
| 10 | RemoveAt(index) | ลบที่ Index ที่กำหนด |
| 11 | RemoveRange(index, count) | ลบช่วงข้อมูล |
| 12 | Reverse() | กลับลำดับ |
| 13 | SetRange(index, ICollection) | แทนที่ช่วงข้อมูล |
| 14 | Sort() | เรียงลำดับ (ใช้ IComparer) |
| 15 | TrimToSize() | ปรับ Capacity ให้เท่ากับ Count |
ตัวอย่าง: เรียงลำดับ ArrayList
using System;
using System.Collections;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
ArrayList arr = new ArrayList();
arr.Add(89);
arr.Add(34);
arr.Add(77);
arr.Add(90);
Console.Write("List: ");
foreach (int i in arr) Console.Write(i + " ");
Console.WriteLine();
arr.Sort(); // เรียงลำดับ
Console.Write("Sorted List: ");
foreach (int i in arr) Console.Write(i + " ");
Console.WriteLine();
Console.ReadKey();
}
}
}
ผลลัพธ์
List: 89 34 77 90
Sorted List: 34 77 89 90
ข้อควรระวัง
- Boxing/Unboxing: เก็บ Value Type (int, double) ต้อง Boxing -> ช้า, ใช้ Memory มาก
- Not Type-Safe: เพิ่ม object อะไรก็ได้ได้ -> Runtime Error ได้
- Deprecated: ใช้
List<T> ใน System.Collections.Generic แทน
เปรียบเทียบ ArrayList vs List<T>
| คุณสมบัติ | ArrayList | List<T> |
| Type Safety | ไม่มี (object) | มี (Compile-time) |
| Performance (Value Types) | ช้า (Boxing) | เร็ว (No Boxing) |
| Namespace | System.Collections | System.Collections.Generic |
| สถานะ | Legacy | Recommended |