如何在 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

更新於: 31-Oct-2023

29K+ 瀏覽量

開啟您的職業生涯

透過完成課程來獲得認證

立即開始
廣告