Created
July 7, 2021 23:42
-
-
Save ElanHasson/2f223a244e53b4758c6ac87f3505fd42 to your computer and use it in GitHub Desktop.
A set of extensions for batching in Linq
This file contains 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 BatchEnumerableExtensions | |
{ | |
public static IEnumerable<IList<T>> InBatchesOf<T>(this IEnumerable<T> items, int batchSize) | |
{ | |
var batch = new List<T>(batchSize); | |
foreach (var item in items) | |
{ | |
batch.Add(item); | |
if (batch.Count >= batchSize) | |
{ | |
yield return batch; | |
batch = new List<T>(batchSize); | |
} | |
} | |
if (batch.Count != 0) | |
{ | |
yield return batch; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment