重命名对象列表中的重复属性条目

时间:2019-01-22 11:30:54

标签: vb.net list duplicates rename

我有一个对象列表,其中每个对象都包含一个字符串属性。这些字符串属性必须是唯一的,因此我尝试将重复的数字添加到其中。首先,我以为this可以帮到我,但这是因为列表而不是对象列表,并且所有尝试将代码转换为vb的尝试都没有成功,所以我尝试了另一种方法。

Object1.String = "Test"
Object2.String = "Test" 

应转换为

Object1.String = "Test"
Object2.String = "Test1"

这是我尝试过的:

Module Module1

    Sub Main()
        Dim obj1 As New TestCls
        Dim obj2 As New TestCls
        Dim obj3 As New TestCls

        obj1.p1 = "Test"
        obj2.p1 = "Test1"
        obj3.p1 = "Test"

        Dim lstmp As New List(Of TestCls)
        lstmp.Add(obj1)
        lstmp.Add(obj2)
        lstmp.Add(obj3)

        For Each elementA As TestCls In lstmp
            For Each elementB As TestCls In lstmp
                If elementA.p1 = elementB.p1 Then
                    elementB.p1 = elementB.p1 & 1
                End If
            Next
        Next
        Dim i As Integer = 0
    End Sub
End Module

Class TestCls
    Public Property p1 As String
End Class

但是结果是Test1和Test111,甚至使许多对象感到困惑。有人可以在这里帮助我吗?

1 个答案:

答案 0 :(得分:2)

您必须增加它而不是始终串联1。我将使用字典来计算每个p1的出现次数。这也可以防止您生成现有p1的错误:

Dim p1Counter = New Dictionary(Of String, Int32)

For Each obj In lstmp
    Dim p1Count As Int32
    Dim containsP1 = p1Counter.TryGetValue(obj.p1, p1Count)
    If containsP1 Then
        p1Count += 1
        Dim newP1 = obj.p1 & p1Count
        While p1Counter.ContainsKey(newP1)
            p1Count += 1
            newP1 = obj.p1 & p1Count
        End While
        obj.p1 = newP1
    Else
        p1Count = 1
    End If
    p1Counter(obj.p1) = p1Count
Next