如何在 C# 中從陣列列表中刪除一個元素?


宣告一個新的 ArrayList 並向其中新增元素。

ArrayList arr = new ArrayList();
arr.Add( "One" );
arr.Add( "Two" );
arr.Add( "Three" );
arr.Add( "Four" );

現在假設你需要刪除元素“Three”。為此,請使用 Remove() 方法。

arr.Remove("Three");

以下是從 ArrayList 中刪除元素的完整示例 -

示例

 線上演示

using System;
using System.Collections;

class Demo {

   static void Main() {
      ArrayList arr = new ArrayList();
      arr.Add( "One" );
      arr.Add( "Two" );
      arr.Add( "Three" );
      arr.Add( "Four" );

      Console.WriteLine("ArrayList...");
      foreach(string str in arr) {
         Console.WriteLine(str);
      }

      arr.Remove("Three");
      Console.WriteLine("ArrayList after removing an element...");

      foreach(string str in arr) {
         Console.WriteLine(str);
      }

      Console.ReadLine();
   }
}

輸出

ArrayList...
One
Two
Three
Four
ArrayList after removing an element...
One
Two
Four

更新時間: 2020 年 6 月 22 日

1K+ 瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.