Home > database >  Comparing every row of two lists of objects for a property and create new object
Comparing every row of two lists of objects for a property and create new object

Time:10-17

Here is what I am trying to do:

Compare every row of compareList with every row of refList

    ----- Do you find 'Leistungscode' of compareList in refList?
     ----- Yes--> Ignore
     ----- No--> New Entry, add to resutList

My problem is that with my for each loop, it creates a new entry every time when Leistungscode doesn't match up, but I need to look through the whole refList first and then add it to the list if I haven't found it. Do you have any idea how to do it?

Here is what I tried:

For Each rowCompare In compareList
    For Each rowRef In refList
        If rowCompare.Leistungscode.CompareTo(rowRef.Leistungscode) = 0 Then

        Else
            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
Next

CodePudding user response:

First I think you should not use CompareTo. CompareTo does extra work determining position. You just need an equals sign.

The empty If, with code only in the else, can be corrected by adding Not to the if.

The real key here is Exit For. Once you find an instance with no match the instance is added to the resultList so we want to stop searching at that point to avoid duplicate entries in the resultList. Exit For only exits the inner For loop. The outer loop will continue with the next element of the commpareList.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each rowCompare In compareList
        For Each rowRef In refList
            If Not rowCompare.Leistungscode = rowRef.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))
                Exit For
            End If
        Next
    Next
    MessageBox.Show(resultList.Count.ToString)
End Sub
  • Related