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

การใช้ Remove, RemoveAt, RemoveRange ใน C# List

List<T> มีเมธอดลบข้อมูลหลายรูปแบบ ใช้ตามสถานการณ์

เมธอดหลัก

MethodคำอธิบายReturnComplexity
Remove(T item)ลบ Item แรกที่ Match (Equality)bool (Removed?)O(n)
RemoveAt(int index)ลบที่ Index ระบุvoidO(n)
RemoveAll(Predicate<T>)ลบทุก Item ที่ Match Conditionint (Count Removed)O(n)
RemoveRange(int index, int count)ลบช่วง Index ถึง Index+Count-1voidO(n)
Clear()ลบทั้งหมดvoidO(n)

ตัวอย่าง: Remove / RemoveAt

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        var animals = new List { "mammals", "reptiles", "amphibians", "vertebrate" };
        
        Console.WriteLine("Initial: " + string.Join(", ", animals));
        // mammals, reptiles, amphibians, vertebrate
        
        // Remove by Value
        bool removed = animals.Remove("reptiles");
        Console.WriteLine($"Remove('reptiles'): {removed}"); // True
        Console.WriteLine("After Remove: " + string.Join(", ", animals));
        // mammals, amphibians, vertebrate
        
        // Remove by Index
        animals.RemoveAt(1); // Index 1 = "amphibians"
        Console.WriteLine("After RemoveAt(1): " + string.Join(", ", animals));
        // mammals, vertebrate
        
        Console.ReadKey();
    }
}

ตัวอย่าง: RemoveRange

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        var numbers = new List { 5, 10, 15, 20, 25, 30, 35 };
        
        Console.WriteLine("Initial: " + string.Join(", ", numbers));
        
        // ลบ 4 ตัวแรก (Index 0-3) — เก็บไว้ 3 ตัวท้าย
        int keepCount = 3;
        int removeCount = Math.Max(0, numbers.Count - keepCount);
        numbers.RemoveRange(0, removeCount);
        
        Console.WriteLine("After RemoveRange(0, 4): " + string.Join(", ", numbers));
        // 20, 25, 30, 35
        
        // ลบกลาง
        numbers.RemoveRange(1, 2); // Index 1, 2 items
        Console.WriteLine("After RemoveRange(1, 2): " + string.Join(", ", numbers));
        // 20, 35
        
        Console.ReadKey();
    }
}

ตัวอย่าง: RemoveAll (Conditional Remove)

var numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// ลบเลขคู่ทั้งหมด
int removed = numbers.RemoveAll(x => x % 2 == 0);
Console.WriteLine($"Removed {removed} items"); // 5
Console.WriteLine(string.Join(", ", numbers)); // 1, 3, 5, 7, 9

⚠️ ข้อควรระวัง

  • Iterating while Removing: ห้าม foreach แล้ว Remove — ใช้ for (int i = list.Count - 1; i >= 0; i--) หรือ RemoveAll
  • Index Out of Range: ตรวจสอบ Index ก่อน RemoveAt/RemoveRange
  • Performance: Remove ที่ Index 0 ช้าที่สุด (Shift ทุก Element) — ใช้ Queue<T> สำหรับ FIFO

Best Practice: Remove While Iterating

// ❌ ผิด: InvalidOperationException
foreach (var item in list) {
    if (ShouldRemove(item)) list.Remove(item);
}

// ✅ ถูก: Reverse For Loop
for (int i = list.Count - 1; i >= 0; i--) {
    if (ShouldRemove(list[i])) list.RemoveAt(i);
}

// ✅ ถูก: RemoveAll (Cleanest)
list.RemoveAll(item => ShouldRemove(item));