如何使用索引從 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

更新於: 2020 年 6 月 22 日

1.2 萬多次瀏覽

開啟你的 職業生涯

透過完成本課程獲得認證

開始學習
廣告