You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

对比两对象列表每行Leistungscode属性生成新对象的实现问题

问题原因

原有代码逻辑存在错误:内层循环每遇到1个不匹配的参考行就直接新增条目,最终同一个对比行只要参考列表有N个不匹配项,就会被重复添加N次,完全不符合「全量遍历参考列表确认无匹配再新增」的需求。

解决方案

方案1:基于原有循环逻辑修改

新增布尔标记位记录是否找到匹配项,遍历完整参考列表后再判断是否需要新增,还可以在找到匹配后直接跳出内层循环减少无效遍历:

For Each rowCompare In compareList
    ' 初始化匹配标记,默认未找到对应编码
    Dim codeExist As Boolean = False
    For Each rowRef In refList
        If rowCompare.Leistungscode.CompareTo(rowRef.Leistungscode) = 0 Then
            codeExist = True
            Exit For
        End If
    Next
    ' 全量遍历参考列表后确认无匹配,再执行新增操作
    If Not codeExist Then
        resultList.Add(New ISAACService(rowCompare.Leistungscode, rowCompare.K_Art, rowCompare.UANR, rowCompare.Ueberbegriff, rowCompare.Benennung, rowCompare.Anzahl, rowCompare.Einheit, rowCompare.Einzelkosten, rowCompare.Summencode))
    End If
Next

方案2:HashSet查找优化(更推荐,数据量较大时性能优势明显)

提前把参考列表的所有Leistungscode存入HashSet集合,直接用O(1)时间复杂度判断编码是否存在,无需每次全量遍历参考列表:

' 提前提取参考列表所有Leistungscode生成HashSet集合
Dim refCodeSet As New HashSet(Of String)(refList.Select(Function(r) r.Leistungscode))

For Each rowCompare In compareList
    ' 直接判断当前编码是否不在参考集合中
    If Not refCodeSet.Contains(rowCompare.Leistungscode) Then
        resultList.Add(New ISAACService(rowCompare.Leistungscode, rowCompare.K_Art, rowCompare.UANR, rowCompare.Ueberbegriff, rowCompare.Benennung, rowCompare.Anzahl, rowCompare.Einheit, rowCompare.Einzelkosten, rowCompare.Summencode))
    End If
Next

注:方案2使用了LINQ语法,需提前导入System.Linq命名空间

内容的提问来源于stack exchange,提问作者user17151986

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 11:54:02