Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lấy hoặc đặt phần tử tại chỉ mục cụ thể trong ArrayList C#

Giới thiệu

ArrayList hỗ trợ indexer [index] để truy cập phần tử theo chỉ mục (0-based). Vì lưu trữ object, cần ép kiểu khi lấy giá trị.

Ví dụ 1: Lấy phần tử tại chỉ mục

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        ArrayList arrList = new ArrayList();
        arrList.Add("Laptop");
        arrList.Add("Desktop");
        arrList.Add("Notebook");
        arrList.Add("Ultrabook");
        arrList.Add("Tablet");
        arrList.Add("Headphone");
        arrList.Add("Speaker");
        
        Console.WriteLine("Elements in ArrayList...");
        foreach (string str in arrList)
        {
            Console.WriteLine(str);
        }
        
        Console.WriteLine("Element at index 5 = " + arrList[5]);
    }
}

Kết quả

Elements in ArrayList...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
Element at index 5 = Headphone

Ví dụ 2: Cập nhật phần tử tại chỉ mục

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        ArrayList arrList = new ArrayList();
        arrList.Add("Laptop");
        arrList.Add("Desktop");
        arrList.Add("Notebook");
        arrList.Add("Ultrabook");
        arrList.Add("Tablet");
        arrList.Add("Headphone");
        arrList.Add("Speaker");
        
        Console.WriteLine("Elements in ArrayList...");
        foreach (string str in arrList)
        {
            Console.WriteLine(str);
        }
        
        Console.WriteLine("Element at index 5 = " + arrList[5]);
        arrList[5] = "SSD";
        Console.WriteLine("Element at index 5 (Updated) = " + arrList[5]);
    }
}

Kết quả

Elements in ArrayList...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
Element at index 5 = Headphone
Element at index 5 (Updated) = SSD

Lưu ý quan trọng

  • Indexer trả về object, cần cast: (string)arrList[0]
  • Gán giá trị kiểu giá trị (int, bool...) sẽ gây boxing
  • Chỉ mục ngoài phạm vi → ArgumentOutOfRangeException
  • ArrayList không an toàn kiểu - khuyến nghị dùng List<T>

So sánh ArrayList vs List<T>

Đặc điểm ArrayList List<T>
Kiểu phần tử object T (generic)
Boxing/Unboxing Có Không
An toàn kiểu Không Có
Hiệu suất Thấp hơn Cao hơn