Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate a list?

Tags:

c#

What's the easiest way to remove every element after and including the nth element in a System.Collections.Generic.List<T>?

like image 430
mpen Avatar asked Sep 23 '10 02:09

mpen


People also ask

How do you truncate a list in Java?

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.

Can you use LEN () on a list?

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.

How do I remove part of a list?

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.


2 Answers

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.

like image 53
Daniel T. Avatar answered Sep 26 '22 00:09

Daniel T.


sans LINQ quicky...

    while (myList.Count>countIWant)         myList.RemoveAt(myList.Count-1); 
like image 22
Tim M. Hoefer Avatar answered Sep 24 '22 00:09

Tim M. Hoefer