How do I truncate a list in C#?

14,110

Solution 1

var itemsOneThroughTwenty = myList.Take(20);
var itemsFiveThroughTwenty = myList.Skip(5).Take(15);

Solution 2

You can use List<T>.GetRange():

var subList = myList.GetRange(0, 20);

From MSDN:

Creates a shallow copy of a range of elements in the source List<T>.

public List<T> GetRange(int index, int count)

Solution 3

This might be helpful for efficiency, if you really want to truncate the list, not make a copy. While the python example makes a copy, the original question really was about truncating the list.

Given a List<> object "list" and you want the 1st through 20th elements

list.RemoveRange( 20, list.Count-20 );

This does it in place. This is still O(n) as the references to each object must be removed, but should be a little faster than any other method.

Solution 4

sans LINQ quicky...

    while (myList.Count>countIWant) 
       myList.RemoveAt(myList.Count-1);
Share:
14,110

Related videos on Youtube

FinDev
Author by

FinDev

Updated on April 28, 2022

Comments

  • FinDev
    FinDev about 2 years

    I know in python you can do something like myList[1:20] but is there anything similar in C#?

  • JaredReisinger
    JaredReisinger over 13 years
    Note that these Linq extensions actually create an IEnumerable<> that stops after N items, rather than creating a new array/list. (This is kind of hidden by using 'var' for the variable type. If the code following the truncation iterates through the new list lots of times, you'll actually be re-evaluating the expression tree each time. In this case, you might want to tack a .ToList() onto the end to force the items to be enumerated and a new list created.
  • Raad
    Raad about 11 years
    As it stands you might consider adding some explanatory text, because less experienced users might struggle to understand your answer.
  • NetMage
    NetMage over 3 years
    Unless the list contains value types, in which case removal of references is skipped in .Net Core.
  • Garr Godfrey
    Garr Godfrey over 3 years
    @NetMage Good point. You are referring to the O(n) and rightly point out this can be O(1) in those cases
  • Garr Godfrey
    Garr Godfrey over 3 years
    not sure what this adds to other answers and the example uses an empty list.