Suppose I have this multidimensional array:
float[][,] vertices = {
new float[,]{ {0f, 1.28f}, {1.28f, 2.56f}, {3.84f, 2.56f}, {5.12f, 1.28f}, {3.84f, 0f}, {1.28f, 0f}, {0f, 1.28f} },
new float[,]{ {0f, 3.83f}, {1.27f, 5.12f}, {3.87f, 5.12f}, {5.12f, 3.83f}, {5.12f, 1.26f}, {3.87f, 0f}, {1.27f, 0f}, {0f, 1.26f}, {0f, 3.83f} }
};
Now, I want to convert each subarray to an array of type Vector2[] where Vector2 is a public class, which simply contains x and y properties:
public class Vector2 {
public float x;
public float y;
public Vector2(float x, float y) { this.x = x; this.y = y }
}
So I want to construct Vector2 elements from Array[2] elements, which are subarrays in above vertices array variable.
I do it like this:
Array.ConvertAll(vertices[0],
new Converter<float[], Vector2>(verticesSequence => { return new Vector2(verticesSequence[0], verticesSequence[1]); }));
However, in return I receive this error message:
Error 15 The best overloaded method match for 'System.Array.ConvertAll(float[][], System.Converter)' has some invalid arguments
You have an array, which contains two arrays, each of which contains a different number of float arrays.
Array.ConvertAll is suitable for converting one array into the other by specifying a mapping delegate (one to one). In this case, you don't only have to convert a single float[,] into a Vector2. Note that you also used a float[] to Vector2 converter, instead of float[,] to Vector2.
Multidimensional arrays like float[,] are also a bit tricky since they don't support LINQ out of the box, which it a bit harder to create a one-liner which would do all the mapping.
In other words, you will at least need a helper method to map the items of the multidimensional array:
public static IEnumerable<Vector2> ConvertVectors(float[,] list)
{
for (int row = 0; row < list.GetLength(0); row++)
{
yield return new Vector2(list[row, 0], list[row, 1]);
}
}
And then you can use that inside the Array.ConvertAll method:
var converted = Array.ConvertAll<float[,], Vector2[]>(
vertices,
ff => ConvertVectors(ff).ToArray());
Honestly, I would prefer a LINQ solution because it will infer all the generic parameters automatically:
var r = vertices
.Select(v => ConvertVectors(v).ToArray())
.ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With