PDA

Click to See Complete Forum and Search --> : problem with objects


nswan
Jan 21st, 2003, 06:07 PM
Hi,

i have the following class

Public Class room
Public roomID As Integer
Public hotelID As Integer
Public size As String
Public singleDouble As String
Public enSuite As Boolean
Public cost As Integer
Public description As String
End Class


and the next class makes a collection of rooms

Public Class rooms
Private mcolRooms As New Collection()

'add a room to our collection
Public Sub add(ByVal room As room, ByVal key As String)
mcolRooms.Add(room, key)
End Sub

'return the number of rooms in our collection
Public ReadOnly Property Count() As Integer
Get
Return mcolRooms.Count
End Get
End Property

'return a room object from our collection
Public ReadOnly Property Item(ByVal IndexOrKey As Object) As room
Get
Return mcolRooms.Item(IndexOrKey)
End Get
End Property

End Class


the problem i have is that i am trying to check to see if a room has been added to the collection already. This would be checked by the roomID(which is added as a key when the add procedure is used). Is there an easy way or do i have to loop through the collection and check each room to see if it exists?

Thanks
Nick

Edneeis
Jan 21st, 2003, 08:10 PM
Well if you are using the collection object then there is no intrinsic way of finding out whether the item is there or not. A lot of the other collection variants can though. Or if you don't want to switch that then you can use error handling to find out the quick way.


Private Function ContainsKey(ByVal col As Collection, ByVal key As String) As Boolean
Try
Dim o As Object = col.Item(key)
Catch
Return False
End Try
Return True
End Function

nswan
Jan 22nd, 2003, 08:16 AM
Thanks Edneeis,

that worked a treat. What are the other types of collections you mentioned though?

Edneeis
Jan 22nd, 2003, 10:26 AM
Check in the help under the System.Collection namespace there are quite a few: SortedList, Hashtable, Dictionary, NameValueCollection...