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 string
s (returns chunks of Type Char
):
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;
List<T> slist = source.ToList();
if (chunksize <= 0 || chunksize >= cnt)
{
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);
}
}
}
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}");
}
chunk 0 : #items 27
chunk 1 : #items 27
chunk 2 : #items 27
chunk 3 : #items 19
History
- 16th October, 2021: Initial version