"Turning" an IEnumerable<IEnumerable<T>> 90 degrees
I'm a little iffy about this implementation. It has side-effects local to the iterator but looks logically clean to me. This assumes each sequence is the same length but should work for any. You can think of it as a variable length Zip()
method. It should perform better than the other linked LINQ solutions found in the other answers as it only uses the minimum operations needed to work. Probably even better without the use of LINQ. Might even be considered optimal.
public static IEnumerable<IEnumerable<T>> Transpose<T>(this IEnumerable<IEnumerable<T>> source)
{
if (source == null) throw new ArgumentNullException("source");
var enumerators = source.Select(x => x.GetEnumerator()).ToArray();
try
{
while (enumerators.All(x => x.MoveNext()))
{
yield return enumerators.Select(x => x.Current).ToArray();
}
}
finally
{
foreach (var enumerator in enumerators)
enumerator.Dispose();
}
}
Take a look at this extension method found here.
/// <summary>
/// Swaps the rows and columns of a nested sequence.
/// </summary>
/// <typeparam name="T">The type of elements in the sequence.</typeparam>
/// <param name="source">The source sequence.</param>
/// <returns>A sequence whose rows and columns are swapped.</returns>
public static IEnumerable<IEnumerable<T>> Transpose<T>(
this IEnumerable<IEnumerable<T>> source)
{
return from row in source
from col in row.Select(
(x, i) => new KeyValuePair<int, T>(i, x))
group col.Value by col.Key into c
select c as IEnumerable<T>;
}
I'm not sure about performance but the code looks elegant.