gpt4 book ai didi

c# - 如何清除列表直到某些项目? C#

转载 作者:太空狗 更新时间:2023-10-29 22:14:45 24 4
gpt4 key购买 nike

我有List<sting>有 5 个条目。 [0],[1],[2],[3],[4].

如果我使用 List.Clear()所有项目都被删除。

我需要删除直到特定项目,例如直到 [1]。这意味着在我的列表中只有 2 items [0] and [1] .如何用 C# 做到这一点?

最佳答案

如果想移除index 1之后的所有项(即只保留前两项):

if (yourList.Count > 2)
yourList.RemoveRange(2, yourList.Count - 2);

如果您需要删除为“[1]”的项目之后的所有项目,无论其索引如何:

int index = yourList.FindIndex(x => x == "[1]");
if (index >= 0)
yourList.RemoveRange(index + 1, yourList.Count - index - 1);

关于c# - 如何清除列表直到某些项目? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6373006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com