public
Created

How to split a list into ‘chunks’ (Fun Code)

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void Main()
{
var items = new List<string>{ "A", "B", "C", "D", "E", "F", "G", "H", "I" };
items.Chunk(2).Dump();
}
 
public static class Ext
{
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int chunkSize)
{
using(var enumerator = source.GetEnumerator()) while(enumerator.MoveNext()) yield return Take(enumerator, chunkSize);
}
private static IEnumerable<T> Take<T>(IEnumerator<T> enumerator, int n)
{
do yield return enumerator.Current; while(--n > 0 && enumerator.MoveNext());
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.