Skip to content

Instantly share code, notes, and snippets.

@TobCap
Last active August 29, 2015 14:01
Show Gist options
  • Save TobCap/d6bcd897926d0d543572 to your computer and use it in GitHub Desktop.
Save TobCap/d6bcd897926d0d543572 to your computer and use it in GitHub Desktop.
transpose a jagged array by linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TransposeArray
{
public static class MyClass
{
public static T[][] Transpose<T>(this T[][] jaggedArray)
{
var elemMin = jaggedArray.Select(x => x.Length).Min();
return jaggedArray
.SelectMany(x => x.Take(elemMin).Select((y, i) => new { val = y, idx = i }))
.GroupBy(x => x.idx, x => x.val, (x, y) => y.ToArray()).ToArray();
}
public static IEnumerable<IEnumerable<T>> Transpose<T>(this IEnumerable<IEnumerable<T>> stream, bool forceElemToArray = false)
{
return stream
.SelectMany(x => x.Select((y, i) => new { val = y, idx = i }))
.GroupBy(x => x.idx, x => x.val, (x, y) => forceElemToArray ? y.ToArray() : y);
}
}
class Program
{
static void Main(string[] args)
{
var values = new [] {
new [] {1,2,3,4},
new [] {5,6,7,8},
new [] {9,10,11,12}
};
foreach (var item in values)
{
Console.WriteLine(string.Join(",", item));
}
Console.WriteLine("");
foreach (var item in values.Transpose())
{
Console.WriteLine(string.Join(",", item));
}
Console.WriteLine("");
var values2 = new[] {
new [] {1,2,3,4},
new [] {5,6},
new [] {9,10,11,12}
};
foreach (var item in values2)
{
Console.WriteLine(string.Join(",", item));
}
Console.WriteLine("");
foreach (var item in values2.Transpose())
{
Console.WriteLine(string.Join(",", item));
}
Console.WriteLine("");
var values3 = Enumerable.Repeat(Enumerable.Range(0, 5), 3);
foreach (var item in values3.Transpose())
{
Console.WriteLine(string.Join(",", item));
}
Console.WriteLine("");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment