2016-04-14 38 views
0

Bunu yapmak için daha hızlı bir yol olup olmadığını merak ediyordum:Nesnelerin bir koleksiyonunu aramanın en hızlı yolu, alana göre

Nesnelerim var. Yeni bir nesne ile sunulduğunda, bu nesnenin dizide var olup olmadığını belirlemek istiyorum (nesnede bir alan kullanarak). Varsa, yalnızca alanlardan birini ekleyin. Varsa, ekleyin.

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 

Yani, belirli bir alan değerine sahip bir nesne, zaten var olmadığını görmek için tüm koleksiyonu üzerinde yineleme olduğunu optimize edilmesi gerekmektedir kısmını tahmin:

İşte benim kodudur.

sayesinde

+0

bir dizi olası bir koleksiyon öğesi denemek ve ayarlamak için daha hızlıdır

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 

ile veya 'Nesnenin' Bir Koleksiyonu'nu? – Comintern

+0

Nesnelerin bir koleksiyonudur. Benim kötü, ben – jason

cevap

1

yerine

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 

hepsine yineleme sonra Nesnesi` `arasında

+0

evet, C & P yazım hatası başlığını düzenleyeceğim. – user3598756

+0

'un dikkatini çektiğiniz için teşekkürler. Bu, işleri hızlandırmaya yardımcı oldu. – jason