Created
December 22, 2015 10:08
-
-
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
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 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