什麼是 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP