How can I transpose a list of lists?
public List<List<T>> Transpose(List<List<T>> lists)
If the inner lists aren't all the same length, I would like to fill the blanks with default(T)
So that the transpose of
new List<List<int>>{
new List<int> {1,2,3},
new List<int> {4,5},
new List<int> {6,7,8,9}
};
Would be
new List<List<int>>{
new List<int> {1,4,6},
new List<int> {2,5,7},
new List<int> {3,0,8},
new List<int> {0,0,9}
};
If you're curious why I don't use a matrix class - in my actual use case the inner type is PropertyDescriptor or String.
Pretty straightforward:
public static List<List<T>> Transpose<T>(List<List<T>> lists)
{
var longest = lists.Any() ? lists.Max(l => l.Count) : 0;
List<List<T>> outer = new List<List<T>>(longest);
for (int i = 0; i < longest; i++)
outer.Add(new List<T>(lists.Count));
for (int j = 0; j < lists.Count; j++)
for (int i = 0; i < longest; i++)
outer[i].Add(lists[j].Count > i ? lists[j][i] : default(T));
return outer;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With