3

using LINQ how can I transform a List of Lists to a new List of Lists where each list has all the elements from the same index.

for example

l[0] = {3,15,22,6}
l[1] = {9,81,52,7}
l[2] = {2,0,32,73}

will turn into

l[0] = {3,9,2}
l[1] = {15,81,0}
l[2] = {22,52,32}
l[3] = {6,7,73}

thanks

gerstla
  • 587
  • 1
  • 5
  • 20
  • I assume the input lists are always going to be the same length? and your output lists in your example seem to have one too many elements (?) – Weyland Yutani Oct 15 '13 at 13:26

3 Answers3

8

You can use this Transpose extension method, from an answer by dtb (I changed the disposing from Array.ForEach to foreach because I find it clearer, and I'm not the only one who doesn't think ForEach methods like that should be used):

public static IEnumerable<IList<T>> Transpose<T>(
    this IEnumerable<IEnumerable<T>> source)
{
    var enumerators = source.Select(e => e.GetEnumerator()).ToArray();
    try
    {
        while (enumerators.All(e => e.MoveNext()))
        {
            yield return enumerators.Select(e => e.Current).ToArray();
        }
    }
    finally
    {
        foreach (var enumerator in enumerators)
            enumerator.Dispose();
    }
}

// e.g. 
IList<IList<int>> l = new int[3][];
l[0] = new []{0,1,2,3};
l[1] = new []{4,5,6,7};
l[2] = new []{8,9,10,11};
l = l.Transpose().ToList();
// l is { { 0, 4, 8 }, { 1, 5, 9 }, { 2, 6, 10 }, { 3, 7, 11 } }
Community
  • 1
  • 1
Tim S.
  • 55,448
  • 7
  • 96
  • 122
4
source
    .SelectMany(list => list.Select((number, index) => Tuple.Create(number, index)))
    .GroupBy(e => e.Item2)
    .OrderBy(g => g.Key)
    .Select(g => g.Select(e => e.Item1).ToList())
    .ToList();
Vladimir
  • 7,345
  • 4
  • 34
  • 39
0
  var largestIndex=list.Max(x=>x.Count);
  var listSize=list.Count;
  var result=Enumerable.Range(0, largestIndex)
                       .Select(i => Enumerable.Range(0, listSize)
                           .Where(x => i < list[x].Count)
                           .Select(j => list[j][i]));
Servy
  • 202,030
  • 26
  • 332
  • 449
Anirudha
  • 32,393
  • 7
  • 68
  • 89