บทความนี้สาธิตวิธีการลบรายการ (element) ที่ดัชนี (index) ที่ระบุจาก StringCollection โดยใช้ method RemoveAt(int index)
ตัวอย่างที่ 1: ลบดัชนี 3
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringCollection stringCol = new StringCollection();
String[] arr = new String[] { "100", "200", "300", "400", "500" };
Console.WriteLine("Array elements...");
foreach (string res in arr)
{
Console.WriteLine(res);
}
stringCol.AddRange(arr);
Console.WriteLine("Total number of elements = " + stringCol.Count);
stringCol.RemoveAt(3); // ลบ index 3 (400)
Console.WriteLine("Total number of elements now = " + stringCol.Count);
}
}
ผลลัพธ์
Array elements... 100 200 300 400 500 Total number of elements = 5 Total number of elements now = 4
ตัวอย่างที่ 2: ลบหลายดัชนีติดต่อกัน
using System;
using System.Collections.Specialized;
public class Demo
{
public static void Main()
{
StringCollection stringCol = new StringCollection();
String[] arr = new String[] { "A", "B", "C", "D", "E" };
Console.WriteLine("Array elements...");
foreach (string res in arr)
{
Console.WriteLine(res);
}
stringCol.AddRange(arr);
Console.WriteLine("Total number of elements = " + stringCol.Count);
stringCol.RemoveAt(1); // ลบ index 1 (B)
stringCol.RemoveAt(2); // ลบ index 2 เดิม (ตอนนี้คือ D เพราะเลื่อนมา)
Console.WriteLine("Total number of elements now = " + stringCol.Count);
}
}
ผลลัพธ์
Array elements... A B C D E Total number of elements = 5 Total number of elements now = 3
คำอธิบายเพิ่มเติม
RemoveAt(int index)ลบรายการที่ดัชนีที่ระบุ (0-based)- โยน
ArgumentOutOfRangeExceptionถ้าดัชนีอยู่นอกช่วง - หลังลบแล้ว รายการถัดไปจะเลื่อนมาทับ (shift left)
- ตัวอย่างที่ 2: ลบ index 1 (B) แล้ว index 2 เดิม (D) จะกลายเป็น index 1, แล้วลบ index 2 ใหม่ (E) จะเหลือ A, C, D
- เวลา complexity: O(n) - ต้องเลื่อนข้อมูล
- Method อื่นๆ:
Remove(string)ลบค่าแรกที่พบ,Clear()ลบทั้งหมด - แนะนำใช้
List<string>แทนสำหรับโค้ดใหม่