Converting multidimensional array elements to different type

寵の児 提交于 2019-11-28 14:09:08

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();

As mentioned in comments the errors you are getting is because you were trying to pass in a multidimensional array instead of a jagged array.

For your needs it may be easier to just use a simple loop

List<Vector2> newList = new List<Vector2>();
foreach (float[,] array in vertices)
    for (int i = 0; i < array.GetLength(0); i++ ) 
        newList.Add(new Vector2(array[i,0], array[i,1]));

Note: this loops through all vertices so the outer loop may not be required for your needs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!