Skip to content

Instantly share code, notes, and snippets.

@mvalipour
Created December 22, 2015 10:08
Show Gist options
  • Save mvalipour/d0da90fc34a31d13789f to your computer and use it in GitHub Desktop.
Save mvalipour/d0da90fc34a31d13789f to your computer and use it in GitHub Desktop.
Slice a collection into chunks with optionally being able to make all chunks fixed size and provide default value for paddings
public static IEnumerable<IEnumerable<T>> Slice<T>(this IEnumerable<T> items, int size, bool fixedSize = false, T defaultValue = default(T))
{
var start = 0;
items = items.ToArray();
var total = items.Count();
while (start < total)
{
var res = items.Skip(start).Take(size).ToList();
while (res.Count < size)
{
res.Add(defaultValue);
}
yield return res;
start += size;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment