28

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

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
FinDev
  • 4,437
  • 6
  • 29
  • 29

6 Answers6

42
var itemsOneThroughTwenty = myList.Take(20);
var itemsFiveThroughTwenty = myList.Skip(5).Take(15);
Tim Robinson
  • 53,480
  • 10
  • 121
  • 138
  • 10
    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. – JaredReisinger Aug 06 '10 at 23:24
29

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)

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Dean Harding
  • 71,468
  • 13
  • 145
  • 180
20

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.

Garr Godfrey
  • 8,257
  • 2
  • 25
  • 23
4

sans LINQ quicky...

    while (myList.Count>countIWant) 
       myList.RemoveAt(myList.Count-1);
Tim M. Hoefer
  • 151
  • 1
  • 3
0
    public static IEnumerable<TSource> MaxOf<TSource>(this IEnumerable<TSource> source, int maxItems)
    {
        var enumerator = source.GetEnumerator();            
        for (int count = 0; count <= maxItems && enumerator.MoveNext(); count++)
        {
            yield return enumerator.Current;
        }
    }
  • As it stands you might consider adding some explanatory text, because less experienced users might struggle to understand your answer. – Raad Mar 06 '13 at 15:01
0

The list can be truncated using the RemoveRange keyword . The function is as follows:

  void List<type>.RemoveRange(int index, int count);

This removes the elements from index until count. Using this for type int, to remove from 0 to the not required points:

Code:

int maxlimit = 100;
List<int> list_1 = new List<int>();
if (list_1.Count > maxLimit){
    list_1.RemoveRange(0, (list_1.Count - maxlimit));
}
David Buck
  • 3,752
  • 35
  • 31
  • 35
aorta
  • 1