ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

IEnumerable.Chunk

Splits an enumerable into chunks of a specified size.

Source

public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> list, int chunkSize)
{
	if (chunkSize <= 0)
	{
		throw new ArgumentException("chunkSize must be greater than 0.");
	}

	while (list.Any())
	{
		yield return list.Take(chunkSize);
		list = list.Skip(chunkSize);
	}
}

Example

var list = new List<int> { 1, 2, 3, 4, 5, 6, 7 };

var chunks = list.Chunk(3);
// returns { { 1, 2, 3 }, { 4, 5, 6 }, { 7 } }

Author: Entroper

Submitted on: 2 aug. 2016

Language: C#

Type: IEnumerable

Views: 17177