Last active
December 15, 2015 05:19
-
-
Save jbogard/5207998 to your computer and use it in GitHub Desktop.
Slice and dice baby
This file contains hidden or 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<TSource>> Slice<TSource>( | |
this IEnumerable<TSource> sequence, | |
int maxItemsPerSlice) | |
{ | |
if (maxItemsPerSlice <= 0) | |
{ | |
throw new ArgumentOutOfRangeException("maxItemsPerSlice", "maxItemsPerSlice must be greater than 0"); | |
} | |
var slice = new List<TSource>(maxItemsPerSlice); | |
foreach (var item in sequence) | |
{ | |
slice.Add(item); | |
if (slice.Count == maxItemsPerSlice) | |
{ | |
yield return slice.ToArray(); | |
slice = new List<TSource>(maxItemsPerSlice); | |
} | |
} | |
// return the "crumbs" that | |
// didn't make it into a full slice | |
if (slice.Count > 0) | |
{ | |
yield return slice.ToArray(); | |
} | |
} | |
public static IEnumerable<IEnumerable<TResult>> Slice<TSource, TResult>( | |
this IEnumerable<TSource> sequence, | |
int maxItemsPerSlice, | |
Func<TSource, TResult> selector) | |
{ | |
if (maxItemsPerSlice <= 0) | |
{ | |
throw new ArgumentOutOfRangeException("maxItemsPerSlice", "maxItemsPerSlice must be greater than 0"); | |
} | |
var slice = new List<TResult>(maxItemsPerSlice); | |
foreach (var item in sequence) | |
{ | |
slice.Add(selector(item)); | |
if (slice.Count == maxItemsPerSlice) | |
{ | |
yield return slice.ToArray(); | |
slice.Clear(); | |
} | |
} | |
// return the "crumbs" that | |
// didn't make it into a full slice | |
if (slice.Count > 0) | |
{ | |
yield return slice.ToArray(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey Jimmy, Michael found a bug in this Slice extension method.
Here is a test that reproduces the issue:
To fix it, create a new List instance and assign it to slice instead of calling slice.Clear();