I would like to create list of child objects from list of parent object. Like If i have list of bookingroom which has one member room then i would like to create list of room from it.
eg. code:
Dim BookingRoomList As List(Of BookingRoom) = New List(Of BookingRoom)
Dim RoomList As List(Of Room) = New List(Of Room)
BookingRoomList = BookingRooms.FillGrid()
For Each Book开发者_如何学运维ingRoomInfo As BookingRoom In BookingRoomList
RoomList.Add(BookingRoomInfo.RoomInfo)
Next
Is there any short cut method instead of iterating over for earch?
You can use Linq and the AddRange
method:
RoomList.AddRange(BookingRoomList.Select(Function(room) room.RoomInfo))
Apart from that, you can shorten the declarations considerably: Dim x As T = New T()
is equivalent to Dim x As New T()
and you should generally prefer the latter.
Furthermore, your instantiation of BookingRoomList
is completely redundant (a logical error) because you overwrite the value later on.
Finally, you can initialise the room list directly in the constructor call, or alternatively you can omit the constructor call entirely – the Linq expression already returns a fully-fledged collection. Which leaves us with:
Dim BookingRoomList As List(Of BookingRoom) = BookingRooms.FillGrid()
Dim RoomList = BookingRoomList.Select(Function(room) room.RoomInfo)).ToList()
And that’s it.
精彩评论