如果要删除索引 1 之后的所有项目(即仅保留前两项):
if (yourList.Count > 2)
yourList.RemoveRange(2, yourList.Count - 2);
Run Code Online (Sandbox Code Playgroud)
如果您需要删除项目后面的值为 "[1]"的所有项目,无论其索引如何:
int index = yourList.FindIndex(x => x == "[1]");
if (index >= 0)
yourList.RemoveRange(index + 1, yourList.Count - index - 1);
Run Code Online (Sandbox Code Playgroud)
您可以使用 List.RemoveWhere(Predicate) .. 或者,您可以执行 for 循环 - 向后循环,删除项目直到您所在的项目,即
for(var i = List.Count()-1; i>=0; i--) {
var item = List[i];
if (item != "itemThatYourLookingFor") {
List.Remove(item);
continue;
}
break;
}
Run Code Online (Sandbox Code Playgroud)