ภาพรวม
List<T> รองรับการเข้าถึงองค์ประกอบผ่านดัชนี (indexer) list[index] ซึ่งทำหน้าที่ทั้ง get (อ่านค่า) และ set (เขียนค่า/อัปเดต) ดัชนีเริ่มต้นที่ 0
ตัวอย่างที่ 1: อ่านค่าที่ดัชนีต่างๆ
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]);
}
}
ผลลัพธ์
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
ตัวอย่างที่ 2: อ่านและอัปเดตค่าที่ดัชนี
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]);
}
}
ผลลัพธ์
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
คำอธิบายเพิ่มเติม
- การเข้าถึงดัชนีที่อยู่นอกช่วง (
index < 0หรือindex >= Count) จะโยนArgumentOutOfRangeException - การ set ค่าที่ดัชนีจะแทนที่ค่าเดิมทันที ไม่ขยายขนาดรายการ
- List<T> ให้การเข้าถึงแบบสุ่ม (random access) O(1) เหมาะสำหรับการอ่าน/เขียนบ่อยครั้ง
- สำหรับการแทรก/ลบกลางรายการ ให้ใช้
Insert()และRemoveAt()ซึ่งมีค่าใช้จ่าย O(n)