-1

I want to rearrange a nested list, group each items of the same index from list into a list.

Here is what I want to achieve.

INPUT

{
["a", "b", "c"], 
["m", "n", "o"],
["x", "y", "z"],
}

OUTPUT

{
["a", "m", "x"], 
["b", "n", "y"],
["c", "o", "z"],
}

How do I achieve this using C#?

Abdullahi
  • 21
  • 2

2 Answers2

2

You can use selector with index and GroupBy:

var x = new[]{new[]{"a", "b", "c"}, new[]{"m", "n", "o"}, new[]{"x", "y", "z"}, };
var arrs = x
    .SelectMany(arr => arr.Select((inner, i) => (inner, i))) // project inner elements with index & flatten
    .GroupBy(i => i.i) // group by element index
    .Select(g => g.Select(gi => gi.inner).ToArray()) // select element from projection
    .ToArray();
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
0

The operation you want to perform is called transposition.

Below solution assumes that all arrays inside are of the same length:

var listOfArrays = new List<string[]>(){
    new string[]{"a", "b", "c"}, 
    new string[]{"m", "n", "o"},
    new string[]{"x", "y", "z"},
};
var transposed = new List<string[]>();
var internalSize = listOfArrays[0].Length;
for(int i = 0; i < internalSize; i++)
{
    var column = new List<string>();
    foreach(var array in listOfArrays)
    {
        column.Add(array[i]);
    }
    transposed.Add(column.ToArray());
}
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69