Skip to content

Instantly share code, notes, and snippets.

@jpreece6
Created January 10, 2017 08:59
Show Gist options
  • Save jpreece6/f54c32fef1609618b49ff16100638f88 to your computer and use it in GitHub Desktop.
Save jpreece6/f54c32fef1609618b49ff16100638f88 to your computer and use it in GitHub Desktop.
List extension to split lists into chunks (good for batch processing on threads)
public static class ExtensionMethods
{
public static List<List<T>> Split<T>(this IEnumerable<T> collection, int size)
{
var chunks = new List<List<T>>();
var count = 0;
var temp = new List<T>();
foreach (var element in collection)
{
if (count++ == size)
{
chunks.Add(temp);
temp = new List<T>();
count = 1;
}
temp.Add(element);
}
chunks.Add(temp);
return chunks;
}
}
// Usage:
// var nums = new List<int>() {1, 2, 3, 4, 5, 6};
// var chunks = nums.Split(3); // Splits into lists containing 3 elements each
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment