What's the easiest way to remove every element after and including the nth element in a System.Collections.Generic.List<T>
?
Method. Truncate a list to a size by removing elements at its end, if necessary. if (limit > items. size()) { return new ArrayList<>(items); final List<T> truncated = new ArrayList<>(limit); for (final T item : items) { truncated.
A list is identifiable by the square brackets that surround it, and individual values are separated by a comma. To get the length of a list in Python, you can use the built-in len() function.
There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.
If you can use RemoveRange
method, simply do:
list.RemoveRange(index, count);
Where index is where to start from and count is how much to remove. So to remove everything from a certain index to the end, the code will be:
list.RemoveRange(index, list.Count - index);
Conversely, you can use:
list.GetRange(index, count);
But that will create a new list, which may not be what you want.
sans LINQ quicky...
while (myList.Count>countIWant) myList.RemoveAt(myList.Count-1);
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