什麼是 C# 列表中的 Add 和 Remove 方法?


List<T> 是 C# 中的一個集合,是一個泛型集合。C# 列表中的 add 和 remove 方法用於新增和刪除元素。

讓我們看看如何在 C# 中使用 Add() 方法。

示例

 即時演示

using System;
using System.Collections.Generic;
class Program {
   static void Main() {
      List<string> sports = new List<string>();
      sports.Add("Football");
      sports.Add("Tennis");
      sports.Add("Soccer");
      foreach (string s in sports) {
         Console.WriteLine(s);
      }
   }
}

輸出

Football
Tennis
Soccer

讓我們看看如何在 C# 中使用 Remove() 方法。

示例

 即時演示

using System;
using System.Collections.Generic;
class Program {
   static void Main() {
      List<string> sports = new List<string>();
      sports.Add("Football"); // add method
      sports.Add("Tennis");
      sports.Add("Soccer");
      Console.WriteLine("Old List...");
      foreach (string s in sports) {
         Console.WriteLine(s);
      }
      Console.WriteLine("New List...");
      sports.Remove("Tennis"); // remove method
      foreach (string s in sports) {
         Console.WriteLine(s);
      }
   }
}

輸出

Old List...
Football
Tennis
Soccer
New List...
Football
Soccer

更新日期:2020 年 6 月 23 日

824 次瀏覽

啟動你的 事業

完成課程獲得認證

開始
廣告
© . All rights reserved.