Skip to content

Instantly share code, notes, and snippets.

@ismaelhamed
Created May 17, 2013 14:18
Show Gist options
  • Save ismaelhamed/5599320 to your computer and use it in GitHub Desktop.
Save ismaelhamed/5599320 to your computer and use it in GitHub Desktop.
Collection of extensions methods for IEnumerable
public static class IEnumerableExtensions
{
/// <summary>
/// Batches up an enumerable and yields you a sequence of arrays.
/// </summary>
public static IEnumerable<T[]> Batch<T>(this IEnumerable<T> sequence, int batchSize)
{
var batch = new List<T>(batchSize);
foreach (var item in sequence)
{
batch.Add(item);
if (batch.Count >= batchSize)
{
yield return batch.ToArray();
batch.Clear();
}
}
if (batch.Count > 0)
{
yield return batch.ToArray();
batch.Clear();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment