VB.Net两集合相加的实现

要实现的需求:

12

实现代码:

Public Structure sumC
    Public sum_A, sum_B As Integer
End Structure

Public Class sumCollection
    Inherits Dictionary(Of Integer, Integer)

    Public Shared Operator +(a As sumCollection, b As sumCollection) As SortedDictionary(Of Integer, sumC)
        Dim sum As New SortedDictionary(Of Integer, sumC)
        For Each i In a
            'B集合包含A的ID
            If b.ContainsKey(i.Key) Then
                Dim t As sumC
                t.sum_A = i.Value
                t.sum_B = b(i.Key)
                sum.Add(i.Key, t)
            Else
                'B集合没有A的ID
                Dim t As sumC
                t.sum_A = i.Value
                t.sum_B = 0
                sum.Add(i.Key, t)
            End If
        Next

        For Each i In b
            'A集合没有B的ID
            If Not a.ContainsKey(i.Key) Then
                Dim t As sumC
                t.sum_A = 0
                t.sum_B = i.Value
                sum.Add(i.Key, t)
            End If
        Next

        Return sum
    End Operator
End Class

Module Module1
    Sub Main()
        '测试
        Dim A As New sumCollection
        A.Add(1, 4)
        A.Add(3, 6)

        Dim B As New sumCollection
        B.Add(2, 89)
        B.Add(3, 7)

        Dim C = A + B
        For Each i In C
            Console.WriteLine("{0} {1} {2}", i.Key, i.Value.sum_A, i.Value.sum_B)
        Next
        Console.Read()
    End Sub
End Module

运行结果:

result

不允许评论