简体   繁体   中英

Removing first 3 Items from a list

How can I remove n items together from a List?

For example in a List of 10 elements I want to remove 3 items together using a for cicle

If you want to safely remove the first three items:

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

That will remove up to three items, but won't throw an exception if there are fewer than three items in the list. If there are 0, 1, or 2 items in the list it will remove that many.

You want to use Take or Skip . As mentioned in the Docs of Skip:

The Take and Skip methods are functional complements. Given a sequence coll and an integer n, concatenating the results of coll.Take(n) and coll.Skip(n) yields the same sequence as 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);

If you want to have a List instead of an IEnumerable you can use .ToList() on the Enumerable you get back.

You can (and should already have) read about these methods in the docs: 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);
}

As this and this answer already suggests, the better way to do this would be with the RemoveRange method.
Go check out those answers as well.

Just remove first 3 items?

list.RemoveRange(0, 3);

Removes 3 items starting at index=0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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