有两个下拉列表时从特定数组中获取特定值

Get a specific value from a specific array when having two dropdown lists

我有 5 个数组,每个数组代表 1 个城市。数组中的每个位置代表到另一个城市的距离(每个特定城市的所有数组共享相同的位置)。我有两个下拉列表,用户应该从那里 select 两个城市来计算它们之间的距离。 它是这样设置的:

    //                City0, City1, City2, City3, City4
    int[] distanceFromCity0 = { 0, 16, 39, 9, 24 };
    int[] distanceFromCity1 = { 16, 0, 36, 32, 54 };
    int[] distanceFromCity2 = { 39, 36, 0, 37, 55 };
    int[] distanceFromCity3 = { 9, 32, 37, 0, 21 };
    int[] distanceFromCity4 = { 24, 54, 55, 21, 0 };

    int cityOne = Convert.ToInt16(DropDownList1.SelectedValue);
    int cityTwo = Convert.ToInt16(DropDownList2.SelectedValue);

并且在下拉列表中每个城市都有相应的 ID(city0 = 0、city1 = 1 等)

我尝试了几种不同的方法,但其中 none 确实有效。 所以基本上,我如何根据选择 "connect" DropDownList1 到数组之一,然后将 DropDownList2 连接到 selected 数组中的位置之一(来自 DropDownList1 selection)并将其打印到 Label1? 二维数组更容易吗?

这对你来说可能看起来很简单,但我是 C# 的菜鸟。

一种方法是将 distanceFromCity0 ... distanceFromCity4 组合成一个二维数组,并使用两个城市作为距离值的索引:

int[][] distanceBetweenCities = {
    new[]{ 0, 16, 39, 9, 24 },
    new[]{ 16, 0, 36, 32, 54 },
    new[]{ 39, 36, 0, 37, 55 },
    new[]{ 9, 32, 37, 0, 21 },
    new[]{ 24, 54, 55, 21, 0 }
};

int cityOne = Convert.ToInt32(DropDownList1.SelectedValue);
int cityTwo = Convert.ToInt32(DropDownList2.SelectedValue);
var distance = distanceBetweenCities[cityOne][cityTwo];

是的,使用二维数组非常容易。你可以把它看成一个矩阵。一些代码如下:

int[,] distanceMatrix = new int[5, 5] {   { 0, 16, 39, 9, 24 },
                                            { 16, 0, 36, 32, 54 },
                                            { 39, 36, 0, 37, 55 },
                                            { 9, 32, 37, 0, 21 },
                                            { 24, 54, 55, 21, 0 }
                                        };
int cityOne = Convert.ToInt32(DropDownList1.SelectedValue);
int cityTwo = Convert.ToInt32(DropDownList2.SelectedValue);
var distance = distanceMatrix[cityOne, cityTwo]; //the distance between cityOne and cityTwo;