Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

list

split

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.

like image 404
Awesome Avatar asked Apr 08 '11 07:04

Awesome


2 Answers

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)))
      .ToList();

Or you could just use a loop, of course:

public static List<List<T>> Split(List<T> source, int size)
{
    // TODO: Validate that size is >= 1
    // 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.

like image 173
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet


You could use LINQ:

var list = Enumerable.Range(1, 190);
var sublists = list
    .Select((x, i) => new { Index = i, Value = x })
    .GroupBy(x => x.Index / 50)
    .Select(x => x.Select(v => v.Value).ToList())
    .ToArray();
like image 40
Darin Dimitrov Avatar answered Oct 05 '22 22:10

Darin Dimitrov