如何使用索引從 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