15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

350<br />

Using a Collection<br />

When you add data to a collection, you can optionally also assign a key to<br />

that data, which you can later use to search and retrieve that data again. So<br />

if you wanted to add the data Mike Ross along with the key moron, you<br />

could use the following command:<br />

HitList.Add (“Mike Ross”, “moron”)<br />

When adding a key to data in a collection, your key must meet these criteria:<br />

✦ You must add a key at the same time you add data to a collection.<br />

After you add data to a collection, you can’t go back later and add a key<br />

to that data.<br />

✦ Every key must be a string.<br />

✦ Every key must be unique; no two items in a collection can share the<br />

same key.<br />

Searching and retrieving data<br />

After you store data in a collection, here are two ways to search and retrieve<br />

data from that collection:<br />

✦ Use the index number of that data.<br />

✦ Use the key of that data.<br />

If you don’t store a key with data originally, you can’t retrieve that data with<br />

a key.<br />

Index numbers<br />

To retrieve data based on its location, you can do something as simple as<br />

the following:<br />

Dim Junk as New Collection<br />

Junk.Add (3.1415)<br />

Junk.Add (99)<br />

Junk.Add (“Bo”)<br />

If you wanted to retrieve the name Bo from the collection, you’d have to<br />

know that Bo is stored as the third item (index number 3), so the following<br />

would store the string Bo in the Good variable:<br />

Good = Junk.Item(3)<br />

The problem with relying on index numbers alone is that as you add and<br />

delete items from a collection, the index numbers may change, as shown in<br />

Figure 3-6.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!