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

12K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.