0

我正在努力弄清楚如何observableCollection在以下情况下删除和添加:

    Dim flightsColl As New ObservableCollection(Of Flight)
    Dim f1 As Flight = New Flight With {.FlightName = "Jet1"}
    Dim f2 As Flight = New Flight With {.FlightName = "Boeing"}

    Dim p1 As Passenger = New Passenger() With {.Name = "Tim", .Address = "address1"}
    Dim p2 As Passenger = New Passenger() With {.Name = "Tom", .Address = "address2"}
    Dim p3 As Passenger = New Passenger() With {.Name = "Tas", .Address = "address3"}

    'add 2 passangers to Jet1

    f1.Passengers.Add(p1)
    f1.Passengers.Add(p2)

    'add passnger3 to boeing
    f2.Passengers.Add(p3)

    'add flight1 & 2 to flight list
    flightsColl.Add(f1)
    flightsColl.Add(f2)  

在上面的例子中,我有一个航班collection,它是一个可观察的集合。
如您所见,它有 2 个航班,第一个有 2 个乘客,第二个有 1 个乘客

现在,如果我必须将乘客 2(p2) 转移到航班 2,那么我必须
flightsColl
Remove Passenger 2 from flight 1

Add Passenger 2 to flight 2

更新

Public Class Flight

Public Property Name() As String
Public Property Passengers As ICollection(Of Passenger)


Public Sub New()
    Me.Appliances = New ObservableCollection(Of Passenger)
End Sub

结束类

4

1 回答 1

0

为什么一定要通过flightsColl?您对航班和乘客都有参考。

f1.Passengers.Remove(p2)

... ETC

** 更新 **

Dim oldflight As Flight = flightsColl.FirstOrDefault(Function(f) f.FlightName = "oldFlightName")
Dim passenger As Passenger = oldflight.Passengers.FirstOrDefault(Function(p) p.Name = "passengerName")
oldflight.Passengers.Remove(passenger)

Dim newflight As Flight = flightsColl.FirstOrDefault(Function(f) f.FlightName = "newFlightName")
newflight.Passengers.Add(passenger)

这有帮助吗?您需要在其中添加一些错误检查(如果您不想意外删除同名的其他乘客,SingleOrDefault 会更好)

于 2013-02-28T11:42:16.950 回答