เมธอด Insert(int index, T item) ของ List<T> ใช้แทรกองค์ประกอบเดี่ยวเข้าไปที่ตำแหน่ง (Index) ที่ระบุ องค์ประกอบเดิมที่อยู่ตำแหน่งนั้นและหลังจากนั้นจะถูกเลื่อนไปด้านหลังหนึ่งตำแหน่ง
รูปแบบการใช้งาน
List list = new List { "water", "food", "air" };
list.Insert(1, "shelter"); // แทรกที่ดัชนี 1 (ลำดับที่ 2)
โค้ดตัวอย่างสมบูรณ์
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
List items = new List { "water", "food", "air" };
Console.WriteLine("ลิสต์ต้นฉบับ:");
PrintList(items);
// แทรกที่ตำแหน่งที่ 2 (Index 1)
items.Insert(1, "shelter");
Console.WriteLine("\nหลัง Insert(1, \"shelter\"):");
PrintList(items);
// แทรกหลายตำแหน่ง
items.Insert(0, "oxygen"); // หน้าสุด
items.Insert(items.Count, "sunlight"); // ท้ายสุด (เทียบเท่า Add)
items.Insert(3, "medicine"); // กลาง
Console.WriteLine("\nหลังแทรกหลายตำแหน่ง:");
PrintList(items);
// ตัวอย่าง: Insert เรียงลำดับ (Maintain Sorted Order)
Console.WriteLine("\n--- Insert เรียงลำดับ ---");
List sorted = new List { 10, 20, 30, 40 };
int newValue = 25;
// หาตำแหน่งที่ควรแทรก (Binary Search)
int index = sorted.BinarySearch(newValue);
if (index < 0) index = ~index; // Bitwise complement = ตำแหน่งที่ควรแทรก
sorted.Insert(index, newValue);
Console.WriteLine($"แทรก {newValue} ที่ Index {index}: {string.Join(", ", sorted)}");
// 10, 20, 25, 30, 40
}
static void PrintList(List list)
{
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine($" [{i}] {list[i]}");
}
}
}
ผลลัพธ์
ลิสต์ต้นฉบับ:
[0] water
[1] food
[2] air
หลัง Insert(1, "shelter"):
[0] water
[1] shelter
[2] food
[3] air
หลังแทรกหลายตำแหน่ง:
[0] oxygen
[1] water
[2] shelter
[3] medicine
[4] food
[4] air
[6] sunlight
--- Insert เรียงลำดับ ---
แทรก 25 ที่ Index 2: 10, 20, 25, 30, 40
Insert vs Add vs InsertRange
| เมธอด | พารามิเตอร์ | ตำแหน่ง | คืนค่า |
|---|---|---|---|
Add(item) | T item | ท้ายสุด (Index = Count) | void |
Insert(index, item) | int index, T item | ระบุได้ (0 ถึง Count) | void |
InsertRange(index, coll) | int index, IEnumerable<T> | ระบุได้ | void |
AddRange(coll) | IEnumerable<T> | ท้ายสุด | void |
การใช้งานจริง: Priority Queue แบบง่าย
public class SimplePriorityQueue where T : IComparable
{
private List _items = new List();
public void Enqueue(T item)
{
// หาตำแหน่งที่ควรแทรก (น้อยไปมาก)
int index = _items.BinarySearch(item);
if (index < 0) index = ~index;
_items.Insert(index, item);
}
public T Dequeue()
{
if (_items.Count == 0) throw new InvalidOperationException("Queue empty");
T item = _items[0];
_items.RemoveAt(0);
return item;
}
public int Count => _items.Count;
}
ข้อควรระวัง
indexต้องเป็น 0 ถึงCount(รวม Count = แทรกท้าย)- Index ติดลบหรือ > Count → โยน
ArgumentOutOfRangeException - Complexity: O(n) - ต้องเลื่อนองค์ประกอบหลังตำแหน่งที่แทรก
- แทรกที่ Index 0 บ่อยครั้ง → O(n²) ควรหลีกเลี่ยง หรือใช้
LinkedList<T> - List จะขยาย Capacity อัตโนมัติหากเต็ม
- สำหรับ Sorted List ใช้
BinarySearchหาตำแหน่ง +Insert(O(log n) + O(n))
Insert หลายรายการพร้อมกัน (Bulk Insert)
// แทนที่จะ Insert ทีละตัว (ช้า)
foreach (var item in newItems)
list.Insert(index++, item);
// ใช้ InsertRange (เร็วกว่า - Copy Block เดียว)
list.InsertRange(index, newItems);