FinDev
FinDev

Reputation: 4827

How do I truncate a list in C#?

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

Upvotes: 29

Views: 18373

Answers (6)

aorta
aorta

Reputation: 1

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

Upvotes: 0

Geoduck
Geoduck

Reputation: 9009

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.

Upvotes: 22

Dean Harding
Dean Harding

Reputation: 72668

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)

Upvotes: 30

Luiz Carlos
Luiz Carlos

Reputation: 1

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

Upvotes: 0

Tim M. Hoefer
Tim M. Hoefer

Reputation: 151

sans LINQ quicky...

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

Upvotes: 4

Tim Robinson
Tim Robinson

Reputation: 54764

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

Upvotes: 43

Related Questions