|
-
Dec 22nd, 2000, 11:12 AM
#1
I am trying to write code that adds items to a collection. The problem I face is that I need to determine if an item already exists, I don't want to add it again.
Because of the number of items in the collection, I do not want to loop through them all checking each one.
Is there a way to directly find out if it exists?
Paolo.
-
Jan 1st, 2001, 05:43 PM
#2
Fanatic Member
I'm not sure that can be done.
You can check if something exists in a listbox by setting the Text property to the item you want to check. If ListIndex = -1 then it doesn't exist in the list.
I don't think you can do duplicate searching in collections without looping throught the entire collection.
-
Jan 4th, 2001, 06:26 PM
#3
Member
Here's a possible solution
Enter this code onto a form. It will demonstrate trying to get an object from a collection, using the key value.
The program will error out at the line
item = col.item("iv")
If you trap it with an error trap, then you have your method of quickly checking to see if an object is in a collection.
Does this help?
Samwise Galenorn
[email protected]
Private Sub Form_Load()
Dim item
Dim col as New Collection
col.Add "one", "i"
col.Add "two", "ii"
col.Add "three", "iii"
item = col.item("iii")
MsgBox "item 'iii' is " & item
item = col.item("iv")
MsgBox "item 'iv' is " & item
End Sub
-
Jan 5th, 2001, 10:14 AM
#4
Fanatic Member
If you key the collection and maintain an ordered array of the keys then you can simply check the array at the appropriate insertion point using a quick sort routine or similar, much quicker than looping.
As a point of interest can you order a collection by its keys directly?
Cheers,
P.
Not nearly so tired now...
Haven't been around much so be gentle...
-
Jan 10th, 2001, 06:17 AM
#5
The shortest way
You should work in your collection with keys
If you do this, you can't add to items with the same key in your collection.
Example
Code:
Dim myCol as collection
Set myCol= new Collection
myCol.add "Item 1","x1"
myCol.add "Item 2","x2"
myCol.add "Item 3","x3"
'now if you try this you will get a runtime Error
myCol.add "Item 2","x2"
'It isn't posible to but two Items into a collection with the same Key without remove the old one
-
Jan 13th, 2001, 03:38 PM
#6
New Member
Try this one
If u got a property on the added object, u could use it to flag if it was added. The simplest example is adding Textbox, while adding it, use the Tag property to mark it's added.
If u're adding your own custom obj, add the property yourself (Let/Get)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|