ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Split

somtimes one needs to split a larger collection into multiple smaller ones, this one does so use deferred execution

Source

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);
    }
}

Author: Eckhard Schwabe

Submitted on: 6 mrt. 2009

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 9519