如何从C#中List的指定索引中删除元素?
要从列表的指定索引中删除元素,代码如下-
示例
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args){
List<string> list = new List<string>();
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<string>.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);
}
}
}输出结果
这将产生以下输出-
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
示例
现在让我们来看另一个示例-
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args){
List<int> list = new List<int>();
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);
}
}输出结果
这将产生以下输出-
Count of elements in the List = 5 Count of elements in the List [UPDATED] = 4
热门推荐
10 对生活祝福语简短精辟
11 姥爷生日诗句祝福语简短
12 对离岗同事祝福语简短
13 学生开学季祝福语简短
14 离职横幅升职祝福语简短
15 18岁简短祝福语经典
16 最美婆婆生日祝福语简短
17 生日贺卡祝福语 简短独特
18 老师对学校祝福语简短