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

csharpprogrammingserver side programming更新于 2025/9/20 13:07:17

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"); // 添加方法
      sports.Add(&"Tennis");
      sports.Add(&"Soccer");
      Console.WriteLine(&"Old List...");
      foreach (string s in sports) {
         Console.WriteLine(s);
      }
      Console.WriteLine("新列表...");
      sports.Remove("网球"); // 删除方法
      foreach (string s in sports) {
         Console.WriteLine(s);
      }
   }
}

输出

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

相关文章