当有两个下拉列表时,从特定数组获取特定值
本文关键字:数组 获取 下拉列表 两个 | 更新日期: 2023-09-27 17:50:15
我有5个数组,每个数组代表一个城市。数组中的每个位置表示到另一个城市的距离(对于每个特定的城市,所有数组共享相同的位置)。我有两个下拉列表,用户可以从中选择两个城市来计算它们之间的距离。它是这样设置的:
// 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等)
我试过几种不同的方法,但没有一种真的有效。所以基本上,我如何"连接"DropDownList1到一个数组取决于选择,然后连接DropDownList2到一个位置在选定的数组(从DropDownList1选择),并打印出来的Label1?使用2D数组是否更容易?
这对你来说可能看起来很容易,但我是c#新手。
一种方法是将distanceFromCity0
…将distanceFromCity4
放入单个2D数组中,并使用这两个城市作为距离值的索引:
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;