Skip to content

Instantly share code, notes, and snippets.

@odytrice
Created September 17, 2015 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odytrice/e26370479b470d34b153 to your computer and use it in GitHub Desktop.
Save odytrice/e26370479b470d34b153 to your computer and use it in GitHub Desktop.
Batch Processing Operator for IQueryable and IEnumerables
using System.Collections.Generic;
namespace System.Linq
{
public static class Extensions
{
#region IQueryable Extensions
public static IEnumerable<IQueryable<T>> Batch<T>(this IQueryable<T> query, int batchSize)
{
int count = query.Count();
int batchCount = count <= batchSize ? 1 : (count % batchSize == 0 ? (count / batchSize) : (count / batchSize + 1));
for (int i = 0; i < batchCount; i++)
yield return query.Skip(i * batchSize).Take(batchSize);
}
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> query, int batchSize)
{
int count = query.Count();
int batchCount = count <= batchSize ? 1 : (count % batchSize == 0 ? (count / batchSize) : (count / batchSize + 1));
for (int i = 0; i < batchCount; i++)
yield return query.Skip(i * batchSize).Take(batchSize);
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment