mpen
mpen

Reputation: 283043

How to truncate a list?

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

Upvotes: 38

Views: 31936

Answers (5)

Tim M. Hoefer
Tim M. Hoefer

Reputation: 151

sans LINQ quicky...

    while (myList.Count>countIWant) 
       myList.RemoveAt(myList.Count-1);

Upvotes: 11

Daniel T.
Daniel T.

Reputation: 38410

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.

Upvotes: 63

Kiran Bheemarti
Kiran Bheemarti

Reputation: 1459

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();

    }

Upvotes: 1

zerkms
zerkms

Reputation: 255005

list.Take(n);

Upvotes: 4

Adam Lear
Adam Lear

Reputation: 38778

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);
}

Upvotes: 2

Related Questions