如何在 C# List 中弹出第一个元素?
若要弹出列表中的第一个元素,请使用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
广告