2017-09-05 80 views
-1

我有一個3數組(飲料,食物,沙漠),以及一個名爲價格的多維數組,它存儲菜單上8個項目的價格。我有一個子程序,處理從列表框中的項目轉移到下面的文本框,但考慮到它是多維的價格有問題遍歷多維數組以查找與單維數組匹配的元素

+1

你爲什麼要在不同的陣列中存儲一個物品和它的價格?使用它們的類和集合意味着不必搜索價格。請閱讀[問]並參加[旅遊] – Plutonix

+0

同上@Plutonix。另外,傑克,顯示你的代碼。 –

回答

0

你會更好地考慮你的菜單和每個項目作爲對象例如,菜單包含菜單項目列表,菜單項目是具有屬性的對象,如名稱,類型(飲料/主菜/甜點/面),描述和價格。

所以你可能會更好地創建一個Menu對象,其中包含所有要存儲在其中的菜單項列表。

所以,首先你要定義你的MenuItems是什麼......類似下面的代碼。您還需要定義它是什麼類型的項目。這由Enum..End Enum塊完成。

Friend Class FoodMenuItem 

    Enum ItemType 
     Drink 
     MainCourse 
     Dessert 
     Side 
    End Enum 

    Public Property Name As String 
    Public Property Price As Decimal 
    Public Property Catagory As ItemType 
    Public Property Description As String 

    Public Sub New(newName As String, newPrice As Decimal, newCatagory As ItemType, newDescription As String) 
     Name = newName 
     Price = newPrice 
     Catagory = newCatagory 
     Description = newDescription 
    End Sub 
End Class 

接下來,你要創建一個菜單,是一個簡單的菜單項列表

Dim FoodItems As New List(Of FoodMenuItem) 

到食品項目添加到您需要創建它,並把它添加到您的列表

列表
Dim itemtoAdd1 As New FoodMenuItem("Pasta", 4.95D, FoodMenuItem.ItemType.MainCourse, "Delicious pasta with parmesan cheese") 
Dim itemtoadd2 As New FoodMenuItem("Beer", 3D, FoodMenuItem.ItemType.Drink, "Cool and refreshing") 
Dim itemtoadd3 As New FoodMenuItem("Red Wine", 3.3D, FoodMenuItem.ItemType.Drink, "Fruity") 
Dim itemtoadd4 As New FoodMenuItem("White Wine", 3.5D, FoodMenuItem.ItemType.Drink, "Dry") 
Dim itemtoadd5 As New FoodMenuItem("Salad", 4.5D, FoodMenuItem.ItemType.MainCourse, "Crisp Salad with iceberg lettuce, tomatoes and beetroot") 
Dim itemtoadd6 As New FoodMenuItem("Chocolate Fudge Cake", 4.25D, FoodMenuItem.ItemType.Dessert, "Indulgent fudge cake with fresh whipped cream") 
Dim itemtoadd7 As New FoodMenuItem("Ice Cream", 4.5D, FoodMenuItem.ItemType.Dessert, "In a choice of flavours with the topping of your choice") 

FoodItems.Add(itemtoAdd1) 
FoodItems.Add(itemtoadd2) 
FoodItems.Add(itemtoadd3) 
FoodItems.Add(itemtoadd4) 
FoodItems.Add(itemtoadd5) 
FoodItems.Add(itemtoadd6) 
FoodItems.Add(itemtoadd7) 

因此,在某些時候,您希望將這些項目放在適當的列表框中。您可以使用此子..

​​

而且使用這樣的,假設ListBoxDrinks,ListBoxMainCourse的列表框中的名稱,ListBoxDessert

UpdateList(ListBoxDrinks, FoodMenuItem.ItemType.Drink) 
UpdateList(ListBoxMainCourse, FoodMenuItem.ItemType.MainCourse) 
UpdateList(ListBoxDessert, FoodMenuItem.ItemType.Dessert) 

當您單擊說ListBoxDrinks一個項目,你會得到該項目,並將其名稱放在一個文本框中,並將其價格放在另一個文本框中,如下所示。

Private Sub ListBoxDrinks_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBoxDrinks.SelectedIndexChanged 
    Dim selectedDrink As FoodMenuItem = CType(ListBoxDrinks.SelectedItem, FoodMenuItem) 
    TextBoxItemName.Text = selectedDrink.Name 
    TextBoxItemPrice.Text = selectedDrink.Price.ToString("C") 
End Sub 

應該這樣做。順便提一句ToString("C")在最後一行將文本格式爲您的本地貨幣。