什么是C#列表中的RemoveAt方法?
C#中的RemoveAt()方法用于在您设置的位置处删除列表中的元素。
首先,在列表中设置元素-
var subjects = new List(); subjects.Add("Physics"); subjects.Add("Chemistry"); subjects.Add("Biology"); subjects.Add("Science");
要删除元素,请在要消除该元素的位置设置索引。以下是从第三位置删除元素-
subjects.RemoveAt(2);
让我们看完整的代码-
示例
using System; using System.Collections.Generic; public class Demo { public static void Main(string[] args) { var subjects = new List(); subjects.Add("Physics"); subjects.Add("Chemistry"); subjects.Add("Biology"); subjects.Add("Science"); Console.WriteLine("ELEMENTS:"); foreach (var sub in subjects) { Console.WriteLine(sub); } // remove element at 3rd position subjects.RemoveAt(2); Console.WriteLine("After removing an element:"); foreach (var sub in subjects) { Console.WriteLine(sub); } } }
输出结果
ELEMENTS: Physics Chemistry Biology Science After removing an element: Physics Chemistry Science