Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phương thức RemoveAt trong List C#

Phương thức RemoveAt() trong C# dùng để xóa phần tử trong List tại một vị trí (index) chỉ định.

Cú pháp:

list.RemoveAt(index);

Lưu ý: Index base-0 (phần tử đầu tiên có index = 0).

Ví dụ: Xóa phần tử tại vị trí thứ 3 (index = 2)

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main(string[] args)
    {
        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);
        }
        
        // Xóa phần tử tại vị trí thứ 3 (index 2)
        subjects.RemoveAt(2);
        
        Console.WriteLine("After removing an element:");
        foreach (var sub in subjects)
        {
            Console.WriteLine(sub);
        }
    }
}

Kết quả

ELEMENTS:
Physics
Chemistry
Biology
Science
After removing an element:
Physics
Chemistry
Science

Phương thức liên quan: Remove(item) xóa theo giá trị, Clear() xóa toàn bộ, RemoveRange(index, count) xóa một dải phần tử.