Phương thức RemoveAt trong C# dùng để xóa phần tử trong list tại vị trí chỉ định.
Trước tiên thiết lập phần tử trong list:
var subjects = new List<string>();
subjects.Add("Physics");
subjects.Add("Chemistry");
subjects.Add("Biology");
subjects.Add("Science");
Để xóa phần tử, set index muốn xóa. Xóa phần tử tại vị trí thứ 3 (index 2):
subjects.RemoveAt(2);
Code hoàn chỉnh:
Ví dụ
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
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