Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - List - remove all elements but NOT the first four

Tags:

c#

list

I have a list of elements, however if the number of list elements is greater than 4 I want to remove all elements but leave the first 4 only in the list.

Example:

List<> - 1, 2, 3, 4, 5, 6, 7, 8

The new list should be - 1,2,3,4

I am looking at using List.RemoveAll() but not sure what to put in the parentheses

Looking forward to some help ....

Steven

like image 586
swade1987 Avatar asked May 10 '12 09:05

swade1987


1 Answers

Why not use List.RemoveRange:

if (list.Count > 4)
{
    list.RemoveRange(4, list.Count - 4);
}

(That's assuming you want to mutate the existing list. If you're happy creating a new sequence, I'd definitely use list.Take(4) as per Adam's suggestion, with or without the ToList call. These days I tend to build queries rather than mutating existing collections.)

like image 130
Jon Skeet Avatar answered Oct 25 '22 10:10

Jon Skeet