How do you transpose dimensions in a 2D collection using LINQ?

c#, linq

Solution

Here's an approach that uses a generator instead of recursion. There's less array construction too, so it might be faster, but that's totally conjecture.

public static IEnumerable<IEnumerable<T>> Transpose<T>(
    this IEnumerable<IEnumerable<T>> @this) 
{
    var enumerators = @this.Select(t => t.GetEnumerator())
                           .Where(e => e.MoveNext());

    while (enumerators.Any()) {
        yield return enumerators.Select(e => e.Current);
        enumerators = enumerators.Where(e => e.MoveNext());
    }
}

Problem

Consider the following structure: ``` IEnumerable<IEnumerable<int>> collection = new[] { new [] {1, 2, 3}, new [] {4, 5, 6}, new [] {7, 8, 9} }; ``` How can I enumerate this collection so that I obtain `IEnumerable<int>` collections made up of the first items, second items, etc.? That is, {1, 4, 7}, {2, 5, 8}, ... (Though the implementation I've chosen is `int[]` objects, assume you only have `IEnumerable<int>` functionality. Thanks.)

Original source