(VB.NET)根据多个属性查找对象列表中的所有重复项

时间:2017-08-17 11:14:25

标签: vb.net

我有一个我创建的CommissionStatement对象列表。我需要创建一个新列表,它只包含基于3个属性的列表中的重复项:Firm;供应商;和总数(即这3个中的每一个必须在2个或更多个对象中相同才能被识别为副本)

Object目前是一个简单的字符串对象。

Private Class CommissionStatement
    Property Provider As String
    Property Firm As String
    Property Source As String
    Property Media As String
    Property Total As String
    Property Received As String
End Class

我有一份所有CommissionStatments的清单如下:

Dim fileLocation As String = importText.Text
        Dim csvText As String = My.Computer.FileSystem.ReadAllText(fileLocation).Replace(", ", " ") 
        Dim providerString As String = ""
        Dim allStatements = New List(Of CommissionStatement)
        Dim countIndex As Integer = 0, maxIndex As Integer = csvText.Split(vbLf).Length
        For Each line As String In csvText.Split(vbLf)
            '' Remove the top row
            countIndex += 1
            If countIndex = 1 Then
                Continue For
            End If
            statementProgress.Value = ((countIndex / maxIndex) * 100)
            '' Build the New commissionStatement object and add it to the allStatements list
            If Not line = "" Then
                Dim commissionStatement = New CommissionStatement
                With commissionStatement
                    .Provider = line.Split(",")(0)
                    .Firm = line.Split(",")(1)
                    .Source = line.Split(",")(2)
                    .Media = line.Split(",")(3)
                    .Total = line.Split(",")(4)
                End With
                providerString &= commissionStatement.Provider & ","
                allStatements.Add(commissionStatement)
            End If
        Next

StackOverflow上的第一篇帖子很抱歉,如果它不是很清楚!重复列表还需要是一个CommissionStatements列表,其中包含基于Firm Provider和Total

的allStatements列表中的重复项

1 个答案:

答案 0 :(得分:0)

最好的办法是使用lambda表达式。以下功能应该按照您的要求进行。

Private Function GetDuplicateCommisionStatements(tempStatement As CommissionStatement) As List(Of CommissionStatement)
    Return allStatements.FindAll(Function(x) x.Firm = tempStatement.Firm And x.Provider = tempStatement.Provider And x.Total = tempStatement.Total)
End Function

并像这样使用..

duplicatelist = GetDuplicateCommisionStatements(testCommisionStatement)

当然使用您自己的对象名称。

顺便提一下,您可以使用With语句缩短sub,如下所示

Private Function GetDuplicateCommisionStatements(tempStatement As CommissionStatement) As List(Of CommissionStatement)
    With tempStatement
        Return allStatements.FindAll(Function(x) x.Firm = .Firm And x.Provider = .Provider And x.Total = .Total)
    End With
End Function