Start learning free

LESSON 114 OF 674 · ARRAYS I

Slicing a List in C#

Lesson

TL ; DR:

list.GetRange(i, count) is a new List with count items, starting at index i. The original List doesn't change.


List<string> letters = new List<string>(new[] {"a", "b", "c", "d", "e"});

List<string> middle = letters.GetRange(1, 3);
// middle is [b, c, d]

// letters is still [a, b, c, d, e]


Full lesson:

Sometimes you need only part of a List, like the first few items. The GetRange method copies that part into a new List.

Careful: it takes a start index and a count, not an end index. So GetRange(1, 3) means three items, starting at index 1.

For the items from index i up to j (not included), the count is j - i. So GetRange(1, 3) gives the items at 1, 2 and 3.

To go to the very end, count what's left after the start:

List<string> tail = letters.GetRange(3, letters.Count - 3);
// tail is [d, e]

The new List is a copy. The original stays as it was.


Your task

runners holds a race's runners, in the order they finished.

Put the first three in a new List named podium. Put everyone else, from index 3 to the end, in one named rest.

The code below prints both, then the length of runners.

Expected output:

Ana Ben Cleo
Dan Eve
5
STEP 1 OF 2
    Ctrl + Enter to check