how to check if object already exists in a list

Viewed 466832

I have a list

  List<MyObject> myList

and I am adding items to a list and I want to check if that object is already in the list.

so before I do this:

 myList.Add(nextObject);

I want to see if nextObject is already in the list.

The object "MyObject" has a number of properties but comparison is based on matching on two properties.

What is the best way to do a check before I add a new "MyObject" to this list of "MyObject"s.

The only solution I thought up was to change from a list to a dictionary and then make the key a concatenated string of the properties (this seems a little unelegant).

Any other cleaner solutions using list or LINQ or something else?

9 Answers

A collection can be used as a dictionary, where the difference is that you don't need to a reference to Microsoft Scripting Runtime or use late binding. Please note that in this case the key must be a string. In my case the key(number) is integer, but declared as string. You can create a custom Boolean function to check if the key exists in the list. There is a good article be Paul Kelly on ExcelMacroMastery.com

' Function to check if item in the collection already exists
Function Exists(coll As Collection, key As String) As Boolean

    On Error GoTo EH

    IsObject (coll.Item(key))
    Exists = True

EH:
End Function

end you can use it like this

For i = 3 To lastRow
    
        ' Ignore the Normal areas
        If rg.Cells(i, 1).value <> "Normal" Then
        
            number = rg.Cells(i, 1).value
            
            ' Check if the area exist in the collection using a custom function Exists
            If Exists(coll, number) = False Then
            
                Set oRiskArea = New clsHighRiskArea
                oRiskArea.number = number
                coll.add key:=oRiskArea.number, Item:=oRiskArea
                
            Else
                Set oRiskArea = coll(number)
            End If
            
            With oRiskArea
        
                .name = rg.Cells(i, 2).value
        
            End With
            
        End If

    Next i
Related