Search code examples
c#arraysmultidimensional-arrayjagged-arrays

How to make jagged array to 2D array C#


I want to make 2D jagged array with different column lengths as 2D array with equal column lengths. I tried converting int[][] to List<List<int>>. For example, How do I make

int[][] = 
{0,1,1},
{1,1,1,1},
{1,1,1,1},
{0,1,1}

To

int[][] = 
{0,1,1,0},
{1,1,1,1},
{1,1,1,1},
{0,1,1,0}  // (inserting 0 to extended space)

Solution

  • You're using int[][] in both times, and not the alternative int[,] so I will ignore terminology and will assume you just want to pad 0's to make everything the same length:

    int[][] arr = ...
    
    int maxLength = arr.Max(x => x.Length);
    var arr2 = arr.Select(x =>
                          {
                              if (x.Length == maxLength)
                                  return x;
                              var y = new int[maxLength];
                              x.CopyTo(y, 0);
                              return y;
                          }).ToArray();
    
    // now arr2 is the same as arr but with uniform lengths and padded 0's at the end
    

    This approach performs many allocations. Another approach would be this:

    List<List<int>> lists = ...
    
    // with linq:
    int maxLength = lists.Max(x => x.Count);
    
    // without-linq:
    int maxLength = 0;
    foreach (var list in lists)
        if (list.Count > maxLength)
            maxLength = list.Count;
    // end without-linq
    
    foreach (List<int> list in lists)
        while (list.Count < maxLength)
            list.Add(0);
    

    Choose the one you like better and better suits your situation.

    You can avoid using Linq (if you want) in the first approach as well, but I didn't bother for that one.