-1

我正在使用 3D 坐标。我将它们全部保存到一个列表中,但要继续使用它们,我需要将它们放入一个多维数组(float[,])中。

我的列表如下所示:

<Coordinates> hp_List = new List<Coordinates>();

public class Coordinates
{
    public float x { get; set; }
    public float y { get; set; }
    public float z { get; set; }
}

我尝试了以下代码:

int R = hp_List.Count();
float[,] hp_array = new float[R, 3];
for(int i=0; i<R; i++)
{
    for (int j = 0; j < hp_List.Count; j++)
    {
        hp_array[i, 0] = hp_List[j].x;
        hp_array[i, 1] = hp_List[j].y;
        hp_array[i, 2] = hp_List[j].z;
    }
}

我也尝试了另一种方式:

for(int i=0; i<R; i++)
{
    foreach (Coordinates hp_position in hp_List)
    {
        hp_array[i, 0] = hp_position.x;
        hp_array[i, 1] = hp_position.y;
        hp_array[i, 2] = hp_position.z;
    }
}

我期望以下输出:

589,5  -75,4  238,4
46,2   173,2  70,9
45,7   173,4  70,9
160,9  75,5   75,4
160    76     75,2
156,1  83,9   73,6

我的实际输出是

156,1
83,9
73,6
156,1
83,9
73,6
156,1
83,9
73,6
156,1
83,9
73,6
156,1
83,9
73,6
156,1
83,9
73,6

如您所见,这是我列表中的最后一个元素。

我不确定我的错误在哪里。

4

2 回答 2

4

两个循环都在遍历列表中的所有元素

for(int i=0; i<R; i++)
{
    for (int j = 0; j < hp_List.Count; j++)
    {
    ////
    }
}

别忘了R == hp_List.Count。这就是为什么数组中的所有行都包含列表的最后三个元素的原因。

尝试丢弃内部循环。

for(int i=0; i<R; i++)
{         
    hp_array[i, 0] = hp_List[i].x;
    hp_array[i, 1] = hp_List[i].y;
    hp_array[i, 2] = hp_List[i].z;
}
于 2019-08-08T12:20:29.283 回答
0
        List<Coordinates> hp_List = new List<Coordinates>
        {
            new Coordinates
            {
                 x = 1,
                 y = 2,
                 z = 3
            },
            new Coordinates
            {
                 x = 4,
                 y = 5,
                 z = 6
            }
        };

        int R = hp_List.Count();
        float[,,] hp_array = new float[R, 1, 3];
        for (int i = 0; i < R; i++)
        {
            for (int j = 0; j < 1; j++)
            {
                hp_array[i, j, 0] = hp_List[j].x;
                hp_array[i, j, 1] = hp_List[j].y;
                hp_array[i, j, 2] = hp_List[j].z;
            }
        }
        Console.WriteLine(string.Format("X Y Z"));
        for (int i =  0; i< R; i++)
        {
            Console.WriteLine(string.Format("{0} {1} {2}", hp_array[i, 0, 0], hp_array[i, 0, 1], hp_array[i, 0, 2]));
        }
        Console.Read();

输出

XYZ

1 2 3

4 5 6

于 2019-08-08T13:19:11.743 回答