首页 > 解决方案 > 结合两个列表,仅记录具有 1 个特定唯一属性的记录

问题描述

我在 Visual Basic 中合并了两个列表。这些列表属于自定义对象。我想要组合的唯一记录是,到目前为止,具有属性的一次与列表中的任何其他对象都不匹配。我已经让它运行起来了。但是,第一个列表只有 1.247 条记录。然而,第二个列表仅缺少 27.000.000 条记录。上一次成功合并这两个列表,用了5个多小时。

通常我用 C# 编写代码。我曾经在那里遇到过类似的问题,并使用 any 功能解决了它。它运行得非常完美而且非常快。正如您在代码中看到的那样,我也在这里尝试过。然而它需要的时间太长了。

Private Function combineLists(list As List(Of Record), childrenlist As List(Of Record)) As List(Of Record) 'list is about 1.250 entries, childrenlist about 27.000.000
    For Each r As Record In childrenlist
        Dim dublicate As Boolean = list.Any(Function(record) record.materiaalnummerInfo = r.materiaalnummerInfo)
        If Not dublicate Then
            list.Add(r)
        End If

    Next

    Return list
End Function

对象 Record 看起来像这样(我不确定如何在 VB 中创建自定义对象,这看起来很糟糕,但它有效):

Public Class Record
    Dim materiaalnummer As String
    Dim type As String 'Config or prefered
    Dim materiaalstatus As String
    Dim children As New List(Of String)

    Public Property materiaalnummerInfo()
        Get
            Return materiaalnummer
        End Get
        Set(value)
            materiaalnummer = value
        End Set
    End Property
    Public Property typeInfo()
        Get
            Return type
        End Get
        Set(value)
            type = value
        End Set
    End Property
    Public Property materiaalstatusInfo()
        Get
            Return materiaalstatus
        End Get
        Set(value)
            materiaalstatus = value
        End Set
    End Property
    Public Property childrenInfo()
        Get
            Return children
        End Get
        Set(value)
            children = value
        End Set
    End Property
End Class

我希望有人能指出我正确的方向以缩短所需的时间。先感谢您。

标签: vb.netlist

解决方案


我不是 100% 确定您希望输出是什么,例如所有差异或只是较大列表中的差异等,但我肯定会尝试使用 LINQ!基本上是用于 vb.net 数据的 sql,因此类似于以下内容:

Dim differenceQuery = list.Except(childrenlist)  
        Console.WriteLine("The following lines are in list  but not childrenlist")  

        ' Execute the query.  
        For Each name As String In differenceQuery  
            Console.WriteLine(name)  
        Next  

另外附注我建议不要将列表之一称为“列表”,因为这是不好的做法,并且是 vb.net 系统上正在使用的名称

编辑

请尝试一下,然后让我知道返回的结果。

 Private Function combineLists(list As List(Of Record), childrenlist As List(Of Record)) As List(Of Record) 'list is about 1.250 entries, childrenlist about 27.000.000

        list.AddRange(childrenlist) 'combines both lists

        Dim result = From v In list Select v.materiaalnummerInfo Distinct.ToList
'result hopefully may be a list with all distinct values.

    End Function

或者,如果您不想合并它们,请不要合并。


推荐阅读