Better way to go from ArrayList to Object()

  • Thread starter Thread starter Chris
  • Start date Start date
C

Chris

I have the following code where I want to return a type Hotel()

Function GetHotel as Hotel()

'... Init Code here

Dim arrH As New ArrayList
Do While Reader.Read
Dim H As New Hotel(Reader.GetString(1), Reader.GetInt32(0))
arrH.Add(H)
Loop
Reader.Close()

Dim Hs(arrH.Count - 1) As Hotel
For ii As Integer = 0 To arrH.Count - 1
Hs(ii) = DirectCast(arrH(ii), Hotel)
Next
Return Hs

End Function

Is this the best way to do this? I guess I could use reDim Preserve but
thought that was an ugly way to do it too? What's best way to do this?

Chris
 
Chris said:
I have the following code where I want to return a type Hotel()

Function GetHotel as Hotel()

'... Init Code here

Dim arrH As New ArrayList
Do While Reader.Read
Dim H As New Hotel(Reader.GetString(1), Reader.GetInt32(0))
arrH.Add(H)
Loop
Reader.Close()

Dim Hs(arrH.Count - 1) As Hotel
For ii As Integer = 0 To arrH.Count - 1
Hs(ii) = DirectCast(arrH(ii), Hotel)
Next
Return Hs

End Function

Is this the best way to do this? I guess I could use reDim Preserve but
thought that was an ugly way to do it too? What's best way to do this?


hs = directcast(arrh.toarray(gettype(hotel)), hotel())


Armin
 
Chris,

I'm not sure about VB.NET but in C# we would use:

Hotel[] hotels = (Hotel[])arrH.ToArray(typeof(Hotel));

Keypoint here is using the .ToArray() method.

Jason
 
Armin said:
hs = directcast(arrh.toarray(gettype(hotel)), hotel())


Armin

Thanks, I just didn't pass in the gettype parameter... maybe if there
was some document somewhere that showed how to use the toarray function...

Oh wait... There it is...

Thanks again
Chris
 
Chris said:
I have the following code where I want to return a type Hotel()

Function GetHotel as Hotel()

'... Init Code here

Dim arrH As New ArrayList
Do While Reader.Read
Dim H As New Hotel(Reader.GetString(1), Reader.GetInt32(0))
arrH.Add(H)
Loop
Reader.Close()

\\\
Return DirectCast(arrH.ToArray(GetType(Hotel)), Hotel())
///
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top