Search code examples
c#linqpivot-tabletranspose

Rotate - Transposing a List<List<string>> using LINQ C#


I'm having a List<List<string>>, which is return from the remote data source (i.e., WCF). So, I need to modify the following data into a user-friendly list using LINQ

The C# Code is

List<List<string>> PersonInfo = new List<List<string>>()
{
    new List<string>() {"John", "Peter", "Watson"},
    new List<string>() {"1000", "1001", "1002"}
}

Appropriate Screen Shot: Existing

enter image description here

I need to rotate the data as like the below Screenshot: Proposed

enter image description here

Kindly assist me how to rotate the data using LINQ C#


Solution

  • This is a simple and flexible solution, it will handle multiple inner lists with any number of dimensions.

    List<List<string>> PersonInfo = new List<List<string>>()
    {
        new List<string>() {"John", "Peter", "Watson"},
        new List<string>() {"1000", "1001", "1002"}
    };
    
    
    var result = PersonInfo
        .SelectMany(inner => inner.Select((item, index) => new { item, index }))
        .GroupBy(i => i.index, i => i.item)
        .Select(g => g.ToList())
        .ToList();