Created
January 10, 2017 08:59
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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