迭代字典直到两个条件

时间:2016-04-26 01:08:24

标签: vb.net dictionary

我有一本字典 - 火车(火车,列表(站)) ... station是具有两个属性Boolean的类(station.src和station.dst)

我想在字典上重复循环,直到字典中的每个电台都有这两个属性相等为真

    Do
        li = New List(Of train)(trains.Keys)
        For Each train In li
            Dim s = trains(train).Item(1)
            If s.name = sorc Then
                s.src = True
                s.dst = True
                GoTo n1
            End If
            lo = New List(Of train)(trains.Keys)
            For Each tr As train In lo
                If s.name_t = trains(tr).Item(2).name_t Then
                    s.src = True
                    trains(tr).Item(2).dst = True
                    GoTo n1
                End If
            Next
            trains.Remove(train)
n1:         Next train
        Loop Until (((each station.src in trains is true and each station.dst in trains is true))))

1 个答案:

答案 0 :(得分:0)

我对你的代码所做的事情有点迷失。我曾希望能够在某种程度上简化它。如果你能解释它背后的逻辑,那将是很棒的。

尽管如此,解决问题的简单方法是:

Loop Until trains.SelectMany(Function (kvp) kvp.Value).All(Function (s) s.src And s.dst)

我有兴趣知道这段代码与你想要的结果有多接近:

Dim sorcs = _
    From kvp In trains
    Where kvp.Value.Item(1).name = sorc
    Select New With { .s1 = kvp.Value.Item(1), .s2 = kvp.Value.Item(2) }

Dim pairs = _
    From kvp1 In trains
    Join kvp2 In trains On kvp1.Value.Item(1).name_t Equals kvp2.Value.Item(2).name_t
    Select New With { .s1 = kvp1.Value.Item(1), .s2 = kvp1.Value.Item(2) }

For Each pair In sorcs.Concat(pairs)
    pair.s1.src = True
    pair.s2.dst = True
Next