Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Get Chunky Now

3.80/5 (3 votes)
15 Oct 2021CPOL 10K  
Create collections of #n sized elements from arrays, lists, and string
This is an extension method that returns an IEnumerable<T> containing #n groups of Type T elements of arrays, lists, and string. In the case of a string: returns an IEnumerable<Char>

In a recent Insider News story, Bite-size-NET-6-Chunk-in-LINQ, the new Chunk features in .NET 6 are discussed. We are mere mortals that don't use the EF database context/pagination functions... have been chunking a long time; my version works with lists/arrays of any type, including DateTime, TimeSpan and single strings (returns chunks of Type Char):

C#
//
// required
using System;
using System.Collections.Generic;
using System.Linq;

public static class ChunkExtensions
{
    public static IEnumerable<List<T>> GetChunks<T>(this IEnumerable<T> source, int chunksize)
    {
        int cnt = source.Count();

        if (cnt == 0) yield return null;

        // required to enable 'GetRange
        List<T> slist = source.ToList();

        if (chunksize <= 0 || chunksize >= cnt) //  alternative ? throw error
        {
            yield return slist;
            yield break;
        }
        
        int rem = cnt % chunksize;
        int lastchunkstart = cnt - rem;

        for (int i = 0; i < lastchunkstart; i += chunksize)
        {
            yield return slist.GetRange(i, chunksize);
        }

        if (rem > 0)
        {
            yield return slist.GetRange(lastchunkstart, rem);
        }
    }
}

// usage example

List<int> ints = Enumerable.Range(0, 100).ToList();

List<List<int>> chunk27 = ints.GetChunks(27).ToList();

for (int i = 0; i < chunk27.Count; i++)
{
    List<int> chunk = chunk27[i];
    Console.WriteLine($"chunk {i} : #items {chunk.Count}");
}

// output:

chunk 0 : #items 27
chunk 1 : #items 27
chunk 2 : #items 27
chunk 3 : #items 19

History

  • 16th October, 2021: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)