Skip to content

Instantly share code, notes, and snippets.

@klumsy
Created June 19, 2013 00:12
Show Gist options
  • Save klumsy/5810679 to your computer and use it in GitHub Desktop.
Save klumsy/5810679 to your computer and use it in GitHub Desktop.
C# extension method that can take an action that takes in a list.. so f(x) where x is a list, and break it up into batches of a certain size and do that action against each batch, either in serial or parallel.
public static IEnumerable<T1> Batch<T,T1>(
this IEnumerable<T> list,
int batchSize,
Func<IEnumerable<T>, IEnumerable<T1>> action,
bool processInParallel = false)
{
int i = 0;
var grpqry = from item in list
group item by (int)i++ / batchSize
into part
select part.AsEnumerable();
var prlqry = (processInParallel) ? grpqry.AsParallel() : grpqry;
return prlqry.SelectMany(x => action(x)) ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment