Search code examples
vb.netarraylistsequential

Sequential search on the same arrayList in vb.net


Public Function Validate(updatedDetailList As List(Of DetailVO)) As Boolean
  Dim matchFound As Boolean = False

  For Each firstUpdatedDetail In updatedDetailList
    For Each nextUpdatedDetail In updatedDetailList
      If firstUpdatedDetail.PROD_ID.Equals(nextUpdatedDetail.PROD_ID) Then
        matchFound = True
      End If
    Next nextUpdatedDetail
  Next firstUpdatedDetail

  Return matchFound
End Function

I have the updatedDetailList as a list which I want to iterate and get the current and next object value and compare both the values. If You find same PROD_ID in the updatedDetailList then return matchFound as TRUE.

Is there any way to get next object in inner For Loop. Like...

For Each firstUpdatedDetail In **updatedDetailList**
  For Each nextUpdatedDetail In **updatedDetailList.Next**
    If firstUpdatedDetail.PROD_ID.Equals(nextUpdatedDetail.PROD_ID) Then
      matchFound = True
    End If
  Next nextUpdatedDetail
Next firstUpdatedDetail

Solution

  • It seems like you are trying to perform a distinct validation, so every item of updatedDetailList must be unique.

    Without changing your approach (i.e using For loop), here is the code:

    For i = 0 to updatedDetailList.Count - 2
      If updatedDetailList(i).PROD_ID.Equals(updatedDetailList(i+1).PROD_ID) Then
        matchFound = True
        Exit For
      End If
    Next
    

    But there is a faster way to perform same - it uses LINQ:

    Dim matchFound As Boolean = updatedDetailList.Distinct.Count <> updatedDetailList.Count