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.
3 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
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; } Comments
I don't think so Rory.
You may have been able to do this if it is a Class[,,] multidimensional array, but the fact that each array could be of different length is going to always be a stumbling block.
Assuming you serialize if as a Class[] + another class to give you the original dimensions, you'll be golden.
[,,]instead?