Search code examples
c#generic-list

Reduce a List<T> to a sublist of itself


How can I achieve the equivalent of

// myList is a List<T>

myList = myList.GetRange(offset, number);

as an in-place statement? (i.e. without creating a new list in the process)


Solution

  • without creating a new list

    How about enumerating the result of a LINQ Skip/Take:

    myList.Skip(offset).Take(number);
    

    If you're looking to make permanent alterations to the list:

    myList.RemoveRange(offset+number, myList.Count - (offset+number));
    myList.RemoveRange(0, offset);
    

    You might find that it's faster to make a new list than remove from an existing one; if you're doing this for performance reasons, be sure to race your horses