Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีใช้ RemoveAt ใน C# List

List<T>.RemoveAt(index) ลบ Element ที่ Index ที่ระบุ (0-based)

ตัวอย่าง

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        var subjects = new List<string>();
        subjects.Add("Physics");
        subjects.Add("Chemistry");
        subjects.Add("Biology");
        subjects.Add("Science");
        
        Console.WriteLine("ELEMENTS:");
        foreach (var sub in subjects)
            Console.WriteLine(sub);
        
        // ลบ Index 2 (รายการที่ 3 = Biology)
        subjects.RemoveAt(2);
        
        Console.WriteLine("\nAfter removing index 2:");
        foreach (var sub in subjects)
            Console.WriteLine(sub);
    }
}

ผลลัพธ์

ELEMENTS:
Physics
Chemistry
Biology
Science

After removing index 2:
Physics
Chemistry
Science

เมธอด Remove ทั้งหมด

Methodคำอธิบาย
Remove(item)ลบ Element แรกที่ Match (คืน bool)
RemoveAt(index)ลบที่ Index ที่ระบุ
RemoveAll(predicate)ลบทั้งหมดที่ Match Condition
RemoveRange(index, count)ลบหลายตัวติดกัน
Clear()ลบทั้งหมด

ข้อยกเว้น (Exceptions)

  • ArgumentOutOfRangeException - Index ติดลบ หรือ >= Count
  • Index ต้องเป็น 0 <= index < Count

Safe Removal Pattern

if (index >= 0 && index < list.Count)
    list.RemoveAt(index);