What's the easiest way to remove every element after and including the nth element in a System.Collections.Generic.List<T>
?
Asked
Active
Viewed 2.8k times
34

mpen
- 272,448
- 266
- 850
- 1,236
-
btw this is a duplicate of http://stackoverflow.com/questions/3428242/how-do-i-truncate-a-list-in-c – PandaWood Jan 25 '11 at 00:12
-
@PandaWood: Yep. But too late now :) Two different solutions too. – mpen Jan 25 '11 at 02:36
-
Question header not so adequate to a question. Truncate in SQL means delete all. So the answer would be `list.Clear();` :) – Pawel Cioch Mar 17 '16 at 15:23
-
@PawelCioch This isn't SQL. And that's exactly why you're supposed to read the question body. Truncate [means](http://www.dictionary.com/browse/truncate) "to shorten". – mpen Mar 17 '16 at 19:04
-
I'm not native English speaker so some words sticks to one technology or one meaning. Never checked Truncate in the dictionary, so the header was a trigger for SQL :) Thanks for pointing it out. – Pawel Cioch Mar 30 '16 at 01:33
5 Answers
60
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.
-
1
-
Heh, I edited my answer before I saw your comment, but yes, that's what you would do. – Daniel T. Sep 23 '10 at 02:52
-
4`RemoveRange` is not a LINQ method, it is an instance method of `List<>`. – Anthony Pegram Sep 23 '10 at 03:15
-
2In my mind it's more length that index. `list.RemoveRange(len, list.Count - len); // save first len elems in list` – CoR Jun 01 '19 at 18:26
-
@CoR - thanks, your comment might have saved 10 minutes of my life! – Vasily Hall Feb 28 '20 at 04:33
-
This is what I was looking for - if you're only removing elements from the end then no data is copied, only internal 'size' field of the list is updated. – Dmitry Avtonomov Oct 18 '22 at 20:41
11
sans LINQ quicky...
while (myList.Count>countIWant)
myList.RemoveAt(myList.Count-1);

Tim M. Hoefer
- 151
- 1
- 3
-
-
@ZarShardan How is it less verbose? You have to check if the index exists and calculate the count. If it would allow giving an index that doesn't exist and a count over what actually exists without throwing an exception it would be easier, but as it is, it is actually more verbose. – selalerer Jan 24 '17 at 07:25
-
@selalerer even with the index check it is only marginally more verbose, but still more efficient.Besides, it communicates the intent better, so easier to read. if(idx < list.Count) list.RemoveRange(idx, list.Count - idx); – Zar Shardan Jan 25 '17 at 14:18
-
this works also on ObservableCollection, while RemoveRange doesn't. – Maverick Meerkat Jul 23 '17 at 11:36
-
This worked very well to truncate a list to match the length of another list. It prevents issues with `RemoveRange` at an index of `.Count - 1` when the length of the leading list is `0` (and thus avoids a condition on the value of `.Count`). – Superman.Lopez May 31 '21 at 13:09
3

NullUserException
- 83,810
- 28
- 209
- 234

zerkms
- 249,484
- 69
- 436
- 539
-
3This method will create a new list instead of editing the existing one, which may or may not be what you want. – Daniel T. Sep 23 '10 at 02:53
-
@Daniel T.: that is why i upvoted your answer just after few seconds you've posted it - because yours is more correct and i did not know that extension method ;-) – zerkms Sep 23 '10 at 03:07
-
2@Daniet T, this does not create a new list. It simply allows you to enumerate a sequence of the umutated original list. – Anthony Pegram Sep 23 '10 at 03:11
-
1@Anthony Pegram: but if the OP needs a `List` as result - he will apply `ToList()` anyway. – zerkms Sep 23 '10 at 03:13
-
1@zerkms, if ToList() were part of your answer, the comment would be correct. But it isn't... so it isn't. – Anthony Pegram Sep 23 '10 at 03:16
-
3-1 What does this method do? Does it return a new list? Does it modify the list? How performatic is it? Is there another way to do it? Which is faster? – BrunoLM Sep 23 '10 at 09:59
-
This is great for truncating a list returned from a function – Karan Harsh Wardhan Feb 05 '19 at 06:46
2
If LINQ is not an option, you can loop through the list backwards:
for(int i = list.Count - 1; i >= index; i--)
{
list.RemoveAt(i);
}

Adam Lear
- 38,111
- 12
- 81
- 101
-
-
1RemoveRange is always available when there's List
, as it has nothing to do with LINQ. – Jon Hanna Sep 23 '10 at 09:55 -
1
Here is the sample app to do it
static void Main(string[] args)
{
List<int> lint = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Console.WriteLine("List Elements");
lint.ForEach(delegate(int i) { Console.WriteLine(i); });
lint.RemoveRange(8, lint.Count - 8);
Console.WriteLine("List Elements after removal");
lint.ForEach(delegate(int i) { Console.WriteLine(i); });
Console.Read();
}

Kiran Bheemarti
- 1,439
- 2
- 12
- 14