2015-05-20 59 views
1

我有5个数组代表每个城市1个城市。数组中的每个位置表示与另一个城市的距离(所有阵列对于每个特定城市都有相同的位置)。我有两个下拉列表,用户应该选择两个城市来计算它们之间的距离。 它的设置是这样的:从两个下拉列表中获取特定数组的特定值

//    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? 二维数组更容易吗?

这可能看起来很容易,但我是C#的noob。

回答

1

一种方法是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]; 
+0

“new []”做什么?我不能像 {{0,16,39,9,24},{16,0,36,32,54},{39,36,0,37,55},{ 32,37,0,21},{24,54,55,21,0}}? – NightWalker

+0

它是'n​​ew int [] {...}'的简写。编译器不需要'int',因为它已经知道类型。如果它使代码更清晰,你可以指定它。尝试像'{{0,16,39,9,24},{16,0,36,32,54} ...'看看会发生什么。 (提示,它会给出一个错误,因为需要'new',这是编译器想要的...... :) –

+0

如何打印出来?它返回错误'不能隐含转换类型'字符串'到'System.Web.UI.WebControls.Label' 名称'distance'在它下面有一个蓝色的错误行,表示类似的东西(它不是英文)'不能分配方法组到隐式类型的局部变量。 我也尝试将'distance'转换为字符串,但是当使用它时,我收到了相同的'System.Web ...'错误。 – NightWalker

0

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

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; 
+0

像在David Arno提供的代码中那样,'new int [5,5]'是否和每个子数组之前都有'new []'做同样的事情?正如我所说,我是一个小菜,所以如果你可以向我解释它,将不胜感激:) – NightWalker

+0

大卫阿诺的阵列是一个铁血阵列。锯齿状数组是其元素是数组的数组。锯齿状阵列的元素可以具有不同的尺寸和大小。锯齿状数组有时被称为“数组阵列”。我写的是一个多维数组。数组可以有多个维度,如矩阵。 – Jackliu91