Search code examples
c#arrayslistmultidimensional-arrayjagged-arrays

How extend a jagged array


I tried to extend a jagged array with Array.AddRange with no success. I don't know why it's not working, I've got no exception but the range of my array not change. Here is the code I use:

public World( ushort[][][] worldMatrice)
{
    // OldWith = 864
    ushort OldWidth = (ushort)worldMatrice.GetLength(0);

    // Extend the matrice to (1024) => only the first level [1024][][]            
    worldMatrice.ToList().Add(new ushort[1024- OldWidth][]);
    // NewWidth = 864 , and should be 1024 ...
    ushort NewWidth = worldMatrice.getLenght(0);
}

Solution

  • https://msdn.microsoft.com/en-us/library/bb397694.aspx

    Array.AddRange() doesn't change the dimensions of an Array, and Array.Length will always return the max number of elements the array can hold, not the total number of non-null elements inside it.

    If you're looking to change the dimensions of the Array, you're likely going to need to transfer the values from the old array to a new Array with dimensions you want.

    int[] newArray = new int[1024];
    Array.Copy(oldArray, newArray, oldArray.Length);
    

    To get the number of non-null elements in the array, use something like

    int count = array.Count(s => s != null);