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

วิธิลบสมาชิกจากดัชนีที่ระบุของ List ใน C#

ภาพรวม

เมธอด List<T>.RemoveAt(Int32) ลบสมาชิกที่ดัชนีที่ระบุ (0-based) และเลื่อนสมาชิกหลังมาหน้า

ตัวอย่าง 1: ลบดัชนี 5 (สมาชิกที่ 6)

using System;
using System.Collections.Generic;

public class Demo {
    public static void Main(String[] args) {
        List list = new List();
        list.Add("Ryan");
        list.Add("Kevin");
        list.Add("Andre");
        list.Add("Tom");
        list.Add("Fred");
        list.Add("Jason");
        list.Add("Jacob");
        list.Add("David");

        Console.WriteLine("Count of elements in the List = " + list.Count);
        Console.WriteLine("Enumerator iterates through the list elements...");
        List.Enumerator demoEnum = list.GetEnumerator();
        while (demoEnum.MoveNext()) {
            string res = demoEnum.Current;
            Console.WriteLine(res);
        }

        list.RemoveAt(5);

        Console.WriteLine("\nCount of elements in the List [UPDATED] = " + list.Count);
        Console.WriteLine("Enumerator iterates through the list elements...[UPDATED]");
        demoEnum = list.GetEnumerator();
        while (demoEnum.MoveNext()) {
            string res = demoEnum.Current;
            Console.WriteLine(res);
        }
    }
}

ผลลัพธ์ตัวอย่าง 1

Count of elements in the List = 8
Enumerator iterates through the list elements...
Ryan
Kevin
Andre
Tom
Fred
Jason
Jacob
David
Count of elements in the List [UPDATED] = 7
Enumerator iterates through the list elements...[UPDATED]
Ryan
Kevin
Andre
Tom
Fred
Jacob
David

ตัวอย่าง 2: List ลบดัชนี 2

using System;
using System.Collections.Generic;

public class Demo {
    public static void Main(String[] args) {
        List list = new List();
        list.Add(25);
        list.Add(50);
        list.Add(75);
        list.Add(100);
        list.Add(200);

        Console.WriteLine("Count of elements in the List = " + list.Count);
        list.RemoveAt(2);
        Console.WriteLine("\nCount of elements in the List [UPDATED] = " + list.Count);
    }
}

ผลลัพธ์ตัวอย่าง 2

Count of elements in the List = 5
Count of elements in the List [UPDATED] = 4

สรุป

  • RemoveAt(index) โยน ArgumentOutOfRangeException หาก index ไม่ถูกต้อง
  • ใช้ Remove(item) ถ้าต้องการลบโดยค่า (ลบตัวแรกที่เจอ)
  • หลังลบ Count ลดลง 1 และดัชนีของสมาชิกหลังเปลี่ยนไป