หากต้องการลบรายการออกจากรายการใน C# โดยใช้ดัชนี ให้ใช้เมธอด RemoveAt()
อันดับแรก ตั้งค่ารายการ −
List<string> list1 = new List<string>() {
"Hanks",
"Lawrence",
"Beckham",
"Cooper",
}; ตอนนี้ลบองค์ประกอบที่ตำแหน่ง 2 นั่นคือดัชนี 1
list1.RemoveAt(1);
ให้เราดูตัวอย่างที่สมบูรณ์ −
ตัวอย่าง
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
List<string> list1 = new List<string>() {
"Hanks",
"Lawrence",
"Beckham",
"Cooper",
};
Console.Write("Initial list...");
foreach (string list in list1) {
Console.WriteLine(list);
}
Console.Write("Removing element from the list...");
list1.RemoveAt(1);
foreach (string list in list1) {
Console.WriteLine(list);
}
}
} ผลลัพธ์
Initial list... Hanks Lawrence Beckham Cooper Removing element from the list... Hanks Beckham Cooper