如何使用索引從 C# 列表中移除一項?
要使用索引從 C# 列表中移除一項,請使用 RemoveAt() 方法。
首先,設定列表 −
List<string> list1 = new List<string>() {
"Hanks",
"Lawrence",
"Beckham",
"Cooper",
};現在,移除第 2 個位置(即索引 1)處的元素
list1.RemoveAt(1);
讓我們來看一個完整示例 −
示例
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
List<string> list1 = new List<string>() {
"Hanks",
"Lawrence",
"Beckham",
"Cooper",
};
Console.Write("Initial list...");
foreach (string list in list1) {
Console.WriteLine(list);
}
Console.Write("Removing element from the list...");
list1.RemoveAt(1);
foreach (string list in list1) {
Console.WriteLine(list);
}
}
}輸出
Initial list... Hanks Lawrence Beckham Cooper Removing element from the list... Hanks Beckham Cooper
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP