簡體   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