Split
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> source, int splitSize) { using (IEnumerator<T> enumerator = source.GetEnumerator()) { while (enumerator.MoveNext()) { yield return InnerSplit(enumerator, splitSize); } } } private static IEnumerable<T> InnerSplit<T>(IEnumerator<T> enumerator, int splitSize) { int count = 0; do { count++; yield return enumerator.Current; } while (count % splitSize != 0 && enumerator.MoveNext()); }Example:
var nums = Enumerable.Range(0, 18); var split = nums.Split(5); foreach (var item in split) { foreach (var inner in item) { Console.WriteLine(inner); } }
Description
somtimes one needs to split a larger collection into multiple smaller ones, this one does so use deferred execution
Details
- Author: Eckhard Schwabe
- Submitted on: 6-3-2009 07:51:35
- Language: C#
- Type: System.Collections.Generic.IEnumerable<T>
- Views: 4359
Double click on the code to select all.