如何从 C# 列表中弹出第一个元素?
要在 列表 中弹出第一个元素,使用 RemoveAt() 方法。此方法将从你要删除的元素位置移除该元素。
设置列表
List<string> myList = new List<string>() { "Operating System", "Computer Networks", "Compiler Design" };
现在使用 RemoveAt(0) 弹出第一个元素
myList.RemoveAt(0);
让我们看看完整的示例。
示例
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<string> myList = new List<string>() { "Operating System", "Computer Networks", "Compiler Design" }; Console.Write("Initial list..."); foreach (string list in myList) { Console.WriteLine(list); } Console.Write("Removing first element from the list..."); myList.RemoveAt(0); foreach (string list in myList) { Console.WriteLine(list); } } }
输出
Initial list... Operating System Computer Networks Compiler Design Removing first element from the list... Computer Networks Compiler Design
广告