ใน C# คลาส List<T> (อยู่ใน System.Collections.Generic) เป็นคอลเลกชันแบบเจเนอริกที่นิยมใช้มากที่สุด มีเมธอด Add() สำหรับเพิ่มสมาชิกที่ท้ายของลิสต์ ทำงานในเวลา O(1) เฉลี่ย (amortized constant time)
ตัวอย่างโค้ด: เพิ่มสตริง
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main(string[] args)
{
List list = new List();
list.Add("One");
list.Add("Two");
list.Add("Three");
list.Add("Four");
list.Add("Five");
list.Add("Six");
list.Add("Seven");
list.Add("Eight");
Console.WriteLine("Enumerator iterates through the list elements...");
List.Enumerator demoEnum = list.GetEnumerator();
while (demoEnum.MoveNext())
{
string res = demoEnum.Current;
Console.WriteLine(res);
}
}
}
ผลลัพธ์
Enumerator iterates through the list elements...
One
Two
Three
Four
Five
Six
Seven
Eight
ตัวอย่างเพิ่มเติม: เพิ่มจำนวนเต็ม
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main(string[] args)
{
List list = new List();
list.Add(50);
list.Add(100);
list.Add(150);
list.Add(200);
list.Add(250);
list.Add(500);
list.Add(750);
list.Add(1000);
list.Add(1250);
list.Add(1500);
Console.WriteLine("Enumerator iterates through the list elements...");
List.Enumerator demoEnum = list.GetEnumerator();
while (demoEnum.MoveNext())
{
int res = demoEnum.Current;
Console.WriteLine(res);
}
}
}
ผลลัพธ์
Enumerator iterates through the list elements...
50
100
150
200
250
500
750
1000
1250
1500
วิธีการเพิ่มข้อมูลอื่นๆ ใน List<T>
Add(T item)- เพิ่มรายการเดี่ยวที่ท้ายAddRange(IEnumerable<T> collection)- เพิ่มหลายรายการพร้อมกันInsert(int index, T item)- แทรกที่ตำแหน่งที่กำหนด (O(n))InsertRange(int index, IEnumerable<T> collection)- แทรกหลายรายการ- Object Initializer:
new List{ 1, 2, 3 } - Collection Expression (C# 12+):
[1, 2, 3]
ข้อดีของ List<T> เทียบ ArrayList
- Type-safe - ตรวจสอบชนิดข้อมูลตอน compile-time
- ไม่ต้อง boxing/unboxing สำหรับ value types (int, struct, etc.)
- ประสิทธิภาพหน่วยความจำดีกว่า
- รองรับ LINQ ได้เต็มที่
- มีเมธอดสะดวกมากมาย เช่น
Find,FindAll,Sort,ConvertAllฯลฯ
เคล็ดลับ
หากทราบจำนวนข้อมูลประมาณการล่วงหน้า ใช้ constructor new List<T>(capacity) เพื่อป้องกันการ resize หลายครั้ง ซึ่งช่วยเพิ่มประสิทธิภาพ