-1

I have a list of integers with 50 items:

List<int> list = CreateList();

How could I split it into chunks of 9 items?

List<List<int>> chunks = CreateChucks(list);

I've written this, is there any better way?

private static List<List<T>> GetChunks<T>(List<T> list, int maxChunkSize = 1000)
    {
        var chunks = new List<List<T>>();

        for (int i = 0; i < list.Count; i = i + maxChunkSize)
        {
            chunks.Add(list.Skip(i).Take(maxChunkSize).ToList());
        }

        return chunks;
    }
The Light
  • 26,341
  • 62
  • 176
  • 258

2 Answers2

4

I suggest you to use Batch operator of MoreLINQ (available from NuGet):

IEnumerable<IEnumerable<int>> chuncks = list.Batch(9);

If you want list of lists, then you can create own extension:

public static List<List<T>> Batch(this IEnumerable<T> source, int batchSize)
{
    List<List<T>> result = new List<List<T>>();
    List<T> batch = new List<T>(batchSize);

    foreach(T item in source)
    {
        if (batch.Count == batchSize)
        {
            result.Add(batch);
            batch = new List<T>(batchSize);                 
        }

        batch.Add(item);
    }

    if (batch.Any())
       result.Add(batch);

    return result;        
}

Your current implementation has big drawback - list.Skip(i) will enumerate source list from beginning for each batch you are adding to result.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • @CodeCaster let it stay here :) I also added explanation why current implementation is not very good. Btw it's better to move this question to http://codereview.stackexchange.com/ because OP already has implementation – Sergey Berezovskiy Jan 10 '14 at 11:38
  • 1
    I like your solution, thanks. – The Light Jan 10 '14 at 11:46
0

Try this,

var list = new List<int>();
for (var i = 0; i < 50; i++)
    list.Add(i);

var chunk = new List<List<int>>();
var chunkSize = list.Count / 9;
for (var i = 0; i < 9; i++)
{
    var p = list.Skip(i * chunkSize).Take(chunkSize).ToList();
    chunk.Add(p);
}
Hadi Sharifi
  • 1,497
  • 5
  • 18
  • 28