Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a C# jagged array to an array and back again

I currently have a jagged array Class[][][] which I want to serialise as a normal Class[] array, then convert back into a Class[][][] array after deserialization. Is it at all possible to convert between the two both ways? The dimensions are of constant sizes.

like image 630
Rory Harvey Avatar asked Nov 29 '25 09:11

Rory Harvey


2 Answers

This is how you can flatten to a 1-dimensional structure:

var jagged = new object[][][];
var flattened = jagged.SelectMany(inner => inner.SelectMany(innerInner => innerInner)).ToArray();

As for going back to multidimensional - this will depend entirely on what it is your trying to achieve/what the data represents

like image 143
Dave Bish Avatar answered Dec 02 '25 01:12

Dave Bish


If you don't mind serializing a flattened array and an array of ints, you can use the following:

public static int[] JaggedSizes<T>(this T[][][] topArray)
{
    List<int> rtn = new List<int>();
    rtn.Add(topArray.Length);
    for (int i = 0; i < topArray.Length; i++)
    {
        var midArray = topArray[i];
        rtn.Add(midArray.Length);
        for (int j = 0; j < midArray.Length; j++)
        {
            var botArray = midArray[j];
            rtn.Add(botArray.Length);
        }
    }
    return rtn.ToArray();
}

// Thanks @Dave Bish
public static T[] ToFlat<T>(this T[][][] jagged)
{
    return jagged.SelectMany(inner => 
        inner.SelectMany(innerInner => innerInner)).ToArray(); 
}

public static T[][][] FromFlatWithSizes<T>(this T[] flat, int[] sizes)
{
    int inPtr = 0;
    int sPtr = 0;
    int topSize = sizes[sPtr++];
    T[][][] rtn = new T[topSize][][];
    for (int i = 0; i < topSize; i++)
    {
        int midSize = sizes[sPtr++];
        T[][] mid = new T[midSize][];
        rtn[i] = mid;
        for (int j = 0; j < midSize; j++)
        {
            int botSize = sizes[sPtr++];
            T[] bot = new T[botSize];
            mid[j] = bot;
            for (int k = 0; k < botSize; k++)
            {
                bot[k] = flat[inPtr++];
            }
        }
    }
    return rtn;
}
like image 41
Rawling Avatar answered Dec 02 '25 00:12

Rawling