Drill

ProblemsC# › warmup

Break a list into fixed-size pieces

mediumwarmupArraysC#

A bulk API takes at most a hundred records per call, so a long list has to be handed over in pieces.

ChunkList(values: list<int>, perChunk: int) → list<list<int>>

C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

public List<List<int>> ChunkList(List<int> values, int perChunk) {
    
}

Worked examples

CallResult
ChunkList(new List<int> { 1, 2, 3, 4, 5 }, 2)new List<List<int>> { new List<int> { 1, 2 }, new List<int> { 3, 4 }, new List<int> { 5 } }
ChunkList(new List<int> { 1, 2, 3, 4 }, 2)new List<List<int>> { new List<int> { 1, 2 }, new List<int> { 3, 4 } }
ChunkList(new List<int> { 1 }, 5)new List<List<int>> { new List<int> { 1 } }
ChunkList(new List<int> { }, 2)new List<List<int>> { }

Hint

Step the index forward by the chunk size and slice, rather than pushing one item at a time.

Reference solution in C#
public List<List<int>> ChunkList(List<int> values, int perChunk) {
    var result = new List<List<int>>();
    if (perChunk <= 0) return result;
    for (int i = 0; i < values.Count; i += perChunk) {
        result.Add(values.GetRange(i, Math.Min(perChunk, values.Count - i)));
    }
    return result;
}

The same problem in another language

More warmup problems in C#