Rotate - Transposing a List<List<string>> using LINQ C#
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();
Here is a generic extension method
public static IEnumerable<IEnumerable<T>> Pivot<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
{
Array.ForEach(enumerators, e => e.Dispose());
}
}
so you can
var result = PersonInfo.Pivot();
Assuming there are only ever 2 lists inside PersonInfo
:
var rotated = PersonInfo[0]
.Zip(PersonInfo[1], (a, b) => new List<string> { a, b }).ToList();
If there can be any number of Lists inside of PersonInfo:
Enumerable.Range(0, PersonInfo[0].Count)
.Select(i => PersonInfo.Select(lst => lst[i]).ToList()).ToList();