如何使用索引从 C# 列表中移除一项?
要使用索引从 C# 列表中移除一项,请使用 RemoveAt() 方法。
首先,设置列表 −
List<string> list1 = new List<string>() { "Hanks", "Lawrence", "Beckham", "Cooper", };
现在,移除第 2 个位置(即索引 1)处的元素
list1.RemoveAt(1);
让我们来看一个完整示例 −
示例
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<string> list1 = new List<string>() { "Hanks", "Lawrence", "Beckham", "Cooper", }; Console.Write("Initial list..."); foreach (string list in list1) { Console.WriteLine(list); } Console.Write("Removing element from the list..."); list1.RemoveAt(1); foreach (string list in list1) { Console.WriteLine(list); } } }
输出
Initial list... Hanks Lawrence Beckham Cooper Removing element from the list... Hanks Beckham Cooper
广告