Я пытаюсь перейти к списку из массива для моей системы поиска комнат в Visual Basic - PullRequest
0 голосов
/ 19 января 2020

Это моя функция, чтобы искать, доступна ли комната или нет, и делать так, чтобы они больше не были доступны, так как это отдельно от моей системы регистрации для моего проекта.

Function RoomAvailableFunc()
                Console.WriteLine("Rooms available:")
                For i = 0 To UBound(Rooms)
                    If roomFits(i) >= amountOfPeople Then
                        If roomAvailable(i) = True Then
                            Price = roomCosts(i) * daysStaying
                            Console.WriteLine(Convert.ToString(Rooms(i)))
                            Console.WriteLine("Maxinum in this room: " & roomFits(i))
                            Console.WriteLine("This room costs £" & Convert.ToString(roomCosts(i)) & " per night")
                            Console.WriteLine("Price for the visit: £" & Price)
                            roomsFound += 1
                        End If
                    End If
                Next i
                If roomsFound <= 0 Then
                    Console.WriteLine("Sorry we have not found any rooms for this criteria!")
                    Console.WriteLine("Please try again!")
                    Console.WriteLine("Press any key to continue..")
                    Console.ReadKey()
                    Main()
                End If
                Console.WriteLine("Which room would you like to pick?")
                Console.Write("> ")
                roomNumber = Convert.ToInt16(Console.ReadLine())

                For i = 0 To UBound(Rooms)

                    If roomNumber = Rooms(i) Then
                        Price = roomCosts(i) * daysStaying
                        roomAvailable(i) = False
                    End If
                Next i
            End Function

1 Ответ

1 голос
/ 20 января 2020

Следует помнить, что сопоставление коллекций по индексу не очень хорошее. Намного лучше создать Class с нужными вам полями. Вместо отдельных массивов для roomFits(), roomCosts() и т. Д. 1017 * у вас есть один класс, подобный этому:

Public Class Room
    Public Property ID As Integer 'System/Database ID
    Public Property RoomNumber As String
    Public Property MaxOccupants As Integer
    Public Property Price As Decimal
    Public Property IsAvailable As Boolean
End Class

А затем список ONE для экземпляров этой комнаты класс:

Dim Rooms As New List(Of Room)()

Когда вы сможете загрузить данные для этого списка, мы можем начать смотреть на фактический метод:

Function SelectRoom(amountOfPeople As Integer, daysStaying As Integer) As Room
    Dim matches = Rooms.Where(Func(r) r.MaxOccupants >= amountOfPeople AndAlso r.IsAvailable).ToList()

    'Don't put the higher level program-flow here. Leave that for the calling method!
    If matches.Count = 0 Then Return Nothing

    Console.WriteLine("Rooms available:")
    For Each r As Room in matches
         Dim Price As Decimal = r.Price * daysStaying
         Console.WriteLine($"{r.RoomNumber}")
         Console.WriteLine($"Maximum in this room: {r.MaxOccupants}")
         Console.WriteLine($"This room costs £{r.Price} per night")
         Console.WriteLine($"Price for the visit: £{Price}")
         Console.WriteLine()
     Next r

     Console.WriteLine("Which room would you like to pick? ")
     Console.Write("> ")
     Dim selectedRoomNumber As String = Console.ReadLine()
     Return matches.FirstOrDefault(Function(r) r.RoomNumber = selectedRoomNumber)          
 End Function

Теперь мы должны изменить код вызова тоже.

Dim selectedRoom As Room = Nothing
Dim triesRemaining As Integer = 3
While selectedRoom Is Nothing AndAlso triesRemaining > 0
    selectedRoom = SelectRoom(amountOfPeople, daysStaying)
    If selectedRoom Is Nothing Then
         triesRemaining -= 1

         Console.Write("No rooms matched this criteria. Try again (Y/N)?" )
         If Console.ReadLine().Trim().ToUpper() = "N" Then
             triesRemaining = 0
         End If
    End If
End While
...