什么是 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