繁体   English   中英

从列表中删除前 3 个项目

[英]Removing first 3 Items from a list

如何从列表中一起删除 n 个项目?

例如,在 10 个元素的列表中,我想使用 for cicle 一起删除 3 个项目

如果要安全删除前三项:

list.RemoveRange(0, Math.Min(3, list.Count));

这将删除最多三个项目,但如果列表中的项目少于三个,则不会引发异常。 如果列表中有 0、1 或 2 个项目,它将删除那么多项目。

您想使用TakeSkip 正如跳过文档中提到的:

Take 和 Skip 方法是功能上的补充。 给定一个序列 coll 和一个整数 n,连接 coll.Take(n) 和 coll.Skip(n) 的结果会产生与 coll 相同的序列。

// this will take the first three elements of your list.
IEnumerable<SomeThing> firstThree = list.Take(3);
// this will take all the elements except for the first three (these will be skipped).
IEnumerable<SomeThing> withoutFirstThree = list.Skip(3);

如果你想要一个List而不是IEnumerable你可以在Enumerable上使用.ToList()你回来。

您可以(并且应该已经)在文档中了解这些方法: Skip and Take

// to remove the items instead of getting the list without them, you can simply do this:
// it will remove the first item three times resulting in removing the first three items.
for (int i = 0; i < 3; i++)
{
    list.RemoveAt(0);
}

正如这个这个答案已经表明的那样,更好的方法是使用RemoveRange方法。
也去看看这些答案。

只删除前 3 项?

list.RemoveRange(0, 3);

index=0开始删除 3 个项目。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM