Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transpose a list of lists, filling blanks with default(T)?

Tags:

c#

.net

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.

like image 318
Colonel Panic Avatar asked Dec 21 '22 12:12

Colonel Panic


1 Answers

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;
}
like image 70
Rawling Avatar answered Mar 02 '23 01:03

Rawling