开发者

How to truncate a list?

What's the easiest way to remove every element after and including the nth element in a System.Collections.Ge开发者_如何学编程neric.List<T>?


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


list.Take(n);


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


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

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜