How do I truncate a list in C#?

2019-04-19 04:49发布

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

标签: c# list truncate
5条回答
贪生不怕死
2楼-- · 2019-04-19 05:11

sans LINQ quicky...

    while (myList.Count>countIWant) 
       myList.RemoveAt(myList.Count-1);
查看更多
Bombasti
3楼-- · 2019-04-19 05:16

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)

查看更多
戒情不戒烟
4楼-- · 2019-04-19 05:18
var itemsOneThroughTwenty = myList.Take(20);
var itemsFiveThroughTwenty = myList.Skip(5).Take(15);
查看更多
Rolldiameter
5楼-- · 2019-04-19 05:19
    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;
        }
    }
查看更多
神经病院院长
6楼-- · 2019-04-19 05:22

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.

查看更多
登录 后发表回答