按字段搜索对象集合的最快方法

Fastest way to search a collection of objects, by field

我想知道是否有更快的方法:

我有一组对象。当出现新对象时,我想确定该对象是否已存在于数组中(通过使用对象中的字段)。如果存在,只需附加其中一个字段。如果不存在,请添加它。

这是我的代码:

If (myCollection.count <= 0) Then
        'collection must be empty, so just add it
        Set myObj= New objClass
        With myObj
            .OBJ_ID = ID
            .first_name = first_name
            .last_name = last_name
            .page_number = pageCounter 'some global variable
        End With
        myCollection.Add myObj, ID
    Else        
        Dim myObj As objClass
        'iterate through collection and see if it already exists
        For Each myObj In myCollection
            'if it does exists, just append one of the fields
            If myObj.OBJ_ID = ID Then
                myObj.page_number = myObj.page_number & "," & pageCounter
                isFound= True
            End If
        Next
        'if it doesn't exists, add it
        If (isFound = False) Then
            Set myObj= New objClass
            With myObj
                .OBJ_ID = ID
                .first_name = first_name
                .last_name = last_name
                .page_number = pageCounter
            End With
            myCollection.Add myObj
        End If
    End If

所以,我想需要优化的部分是遍历整个集合,看看是否已经存在具有给定字段值的对象。

谢谢

替代

For Each myObj In myCollection
    'if it does exists, just append one of the fields
    If myObj.OBJ_ID = ID Then
        myObj.page_number = myObj.page_number & "," & pageCounter
        isFound = True
    End If
Next

On Error Resume Next
Set myObj = myCollection(ID)
On Error GoTo 0
If Not myObj Is Nothing Then
    myObj.page_number = myObj.page_number & "," & pageCounter
    isFound = True
End If

尝试设置一个可能的集合项然后遍历所有项会更快