Awesome Awesome - 11 months ago 42
C# Question

How do I split a list based on index in C#?

I have a list with around 190 elements in it for now. How can I split the list into smaller lists with a max of 50 elements in each list?

The result could be lists of 50, 50, 50 and 40 elements.

Answer Source

Assuming you mean List<T>, you can use the GetRange method repeatedly. Heck, you could do this with LINQ:

var lists = Enumerable.Range(0, (list.Count + size - 1) / size)
      .Select(index => list.GetRange(index * size,
                                     Math.Min(size, list.Count - index * size)))

Or you could just use a loop, of course:

public static List<List<T>> Split(List<T> source, int size)
    // TODO: Prepopulate with the right capacity
    List<List<T>> ret = new List<List<T>>();
    for (int i = 0; i < source.Count; i += size)
        ret.Add(source.GetRange(i, Math.Min(size, source.Count - i)));
    return ret;

This is somewhat more efficient than using GroupBy, although it's limited to List<T> as an input.

We have another implementation using IEnumerable<T> in MoreLINQ in Batch.cs.