Skip to content

Instantly share code, notes, and snippets.

@jonocairns
Created April 30, 2015 22:08
Show Gist options
  • Save jonocairns/4fdfbe629808dd92e0a5 to your computer and use it in GitHub Desktop.
Save jonocairns/4fdfbe629808dd92e0a5 to your computer and use it in GitHub Desktop.
public static class ListExtensions
{
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int chunkSize)
{
Argument.CheckIfNull(source, "source");
Argument.CheckIfNull(chunkSize, "chunkSize");
if (chunkSize <= 0)
{
throw new ArgumentException("chunkSize should be positive", "chunkSize");
}
return source
.Select((x, i) => new { Index = i, Value = x })
.GroupBy(x => x.Index / chunkSize)
.Select(x => x.Select(y => y.Value).ToList())
.ToList();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment