c# - Converting multidimensional array elements to different type -
c# - Converting multidimensional array elements to different type -
suppose have 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, want convert each subarray array of type vector2[]
vector2
public class, contains x
, y
properties:
public class vector2 { public float x; public float y; public vector2(float x, float y) { this.x = x; this.y = y } }
so want build vector2 elements array[2] elements, subarrays in above vertices
array variable.
i this:
array.convertall(vertices[0], new converter<float[], vector2>(verticessequence => { homecoming new vector2(verticessequence[0], verticessequence[1]); }));
however, in homecoming receive error message:
error 15 best overloaded method match 'system.array.convertall(float[][], system.converter)' has invalid arguments
you have array, contains 2 arrays, each of contains different number of float arrays.
array.convertall
suitable converting 1 array other specifying mapping delegate (one one). in case, don't have convert single float[,]
vector2
. note used float[]
vector2
converter, instead of float[,]
vector2
.
multidimensional arrays float[,]
bit tricky since don't back upwards linq out of box, bit harder create one-liner mapping.
in other words, @ to the lowest degree need helper method map items of multidimensional array:
public static ienumerable<vector2> convertvectors(float[,] list) { (int row = 0; row < list.getlength(0); row++) { yield homecoming new vector2(list[row, 0], list[row, 1]); } }
and can utilize within array.convertall
method:
var converted = array.convertall<float[,], vector2[]>( vertices, ff => convertvectors(ff).toarray());
honestly, prefer linq solution because infer generic parameters automatically:
var r = vertices .select(v => convertvectors(v).toarray()) .toarray();
c# arrays multidimensional-array converter
Comments
Post a Comment