Giới thiệu
List<T> hỗ trợ truy cập chỉ mục (indexer) để lấy hoặc đặt giá trị tại vị trí cụ thể. Chỉ mục bắt đầu từ 0. Việc truy cập chỉ mục ngoài phạm vi sẽ ném ArgumentOutOfRangeException.
Ví dụ 1: Lấy phần tử tại các chỉ mục
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main(String[] args)
{
List<String> list = new List<String>();
list.Add("100");
list.Add("200");
list.Add("300");
list.Add("400");
list.Add("500");
list.Add("600");
list.Add("700");
list.Add("800");
list.Add("900");
list.Add("1000");
Console.WriteLine("Element at index 0 = " + list[0]);
Console.WriteLine("Element at index 1 = " + list[1]);
Console.WriteLine("Element at index 2 = " + list[2]);
Console.WriteLine("Element at index 3 = " + list[3]);
Console.WriteLine("Element at index 4 = " + list[4]);
Console.WriteLine("Element at index 5 = " + list[5]);
Console.WriteLine("Element at index 6 = " + list[6]);
Console.WriteLine("Element at index 7 = " + list[7]);
}
}
Kết quả
Element at index 0 = 100 Element at index 1 = 200 Element at index 2 = 300 Element at index 3 = 400 Element at index 4 = 500 Element at index 5 = 600 Element at index 6 = 700 Element at index 7 = 800
Ví dụ 2: Cập nhật phần tử tại chỉ mục
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main(String[] args)
{
List<String> list = new List<String>();
list.Add("100");
list.Add("200");
list.Add("300");
list.Add("400");
list.Add("500");
list.Add("600");
list.Add("700");
list.Add("800");
list.Add("900");
list.Add("1000");
Console.WriteLine("Element at index 0 = " + list[0]);
Console.WriteLine("Element at index 1 = " + list[1]);
Console.WriteLine("Element at index 2 = " + list[2]);
Console.WriteLine("Element at index 3 = " + list[3]);
Console.WriteLine("Element at index 4 = " + list[4]);
Console.WriteLine("Element at index 5 = " + list[5]);
Console.WriteLine("Element at index 6 = " + list[6]);
Console.WriteLine("Element at index 7 = " + list[7]);
list[3] = "450";
Console.WriteLine("Element at index 3 [UPDATED] = " + list[3]);
}
}
Kết quả
Element at index 0 = 100 Element at index 1 = 200 Element at index 2 = 300 Element at index 3 = 400 Element at index 4 = 500 Element at index 5 = 600 Element at index 6 = 700 Element at index 7 = 800 Element at index 3 [UPDATED] = 450
Lưu ý hiệu suất
- Truy cập bằng chỉ mục: O(1) - rất nhanh
- Tìm kiếm bằng giá trị (
IndexOf,Contains): O(n) - Chèn/xóa ở giữa danh sách: O(n) do phải dịch chuyển phần tử