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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With