InGroupsOf<T>

I needed to split a string into key-value pairs.

I was initially just doing a for loop with an incrementer of 2 (akin to VB's "STEP 2").

I came across this code, and never looked back.
Language:
C#
Keywords:
Code Snippet

public static IEnumerable<T[]> InGroupsOf<T>(this IEnumerable<T> parts, int groupSize)

{

    // Ref: http://stackoverflow.com/questions/3254680/c-sharp-string-splitting-breaking-string-up-at-second-comma

 

    IEnumerable<T> partsLeft = parts;

    while (partsLeft.Count() >= groupSize)

    {

        yield return partsLeft.Take(groupSize).ToArray<T>();

        partsLeft = partsLeft.Skip(groupSize);

    }

    yield return partsLeft;

}


Created 2012-09-17
comments powered by Disqus
Login