Created
November 5, 2012 08:38
-
-
Save mikeminutillo/4016067 to your computer and use it in GitHub Desktop.
How to split a list into ‘chunks’ (Fun Code)
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
void Main() | |
{ | |
var items = new List<string>{ "A", "B", "C", "D", "E", "F", "G", "H", "I" }; | |
items.Chunk(2).Dump(); | |
} | |
public static class Ext | |
{ | |
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int chunkSize) | |
{ | |
using(var enumerator = source.GetEnumerator()) while(enumerator.MoveNext()) yield return Take(enumerator, chunkSize); | |
} | |
private static IEnumerable<T> Take<T>(IEnumerator<T> enumerator, int n) | |
{ | |
do yield return enumerator.Current; while(--n > 0 && enumerator.MoveNext()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment