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

คลาส ArrayList ใน C#

คลาส ArrayList ใน C#

ArrayList เป็นคอลเลกชันแบบ Dynamic Array (ขนาดเปลี่ยนแปลงได้) เก็บข้อมูลชนิด object ได้ทุกชนิด อยู่ใน System.Collections Note: Legacy Class - ควรใช้ List<T> แทน

เมธอดสำคัญของ ArrayList

#เมธอดคำอธิบาย
1Add(object)เพิ่มอ็อบเจกต์ท้ายสุด
2AddRange(ICollection)เพิ่มหลายรายการจากคอลเลกชันอื่น
3Clear()ล้างข้อมูลทั้งหมด
4Contains(object)ตรวจสอบว่ามีข้อมูลหรือไม่
5GetRange(index, count)ดึง Sub-ArrayList
6IndexOf(object)หา Index แรกที่เจอ
7Insert(index, object)แทรกที่ Index ที่กำหนด
8InsertRange(index, ICollection)แทรกหลายรายการที่ Index
9Remove(object)ลบรายการแรกที่เจอ
10RemoveAt(index)ลบที่ Index ที่กำหนด
11RemoveRange(index, count)ลบช่วงข้อมูล
12Reverse()กลับลำดับ
13SetRange(index, ICollection)แทนที่ช่วงข้อมูล
14Sort()เรียงลำดับ (ใช้ IComparer)
15TrimToSize()ปรับ 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>

คุณสมบัติArrayListList<T>
Type Safetyไม่มี (object)มี (Compile-time)
Performance (Value Types)ช้า (Boxing)เร็ว (No Boxing)
NamespaceSystem.CollectionsSystem.Collections.Generic
สถานะLegacyRecommended