Recipe 8.18. Inserting an Item into a Collection


Problem

You want to insert a new item in the middle of a collection, rather than just adding it to the end of the collection.

Solution

Sample code folder: Chapter 08\Collections

Use the Add() method, but include its optional parameters to control the insertion point.

Discussion

The Add() method by default appends items to the end of a collection, but optional parameters can modify this behavior. Here's the general syntax of the Add() method:

 variable.Add(content, key, before, after) 

All parameters other than content are optional, and you can't supply values for both before and after in the same statement. before and after represent the element positions before or after which the new item should be inserted. In the next code example, the word "slightly" is inserted after position 3 because the after parameter passed to the Add() method is a 3. The word "longer" is then inserted into the collection before the fifth position, because the before parameter of the Add() method is a 5:

 Dim result As New System.Text.StringBuilder Dim wordCollection As New Collection ' ----- Start with a basic collection. wordCollection.Add("This") wordCollection.Add("is") wordCollection.Add("a") wordCollection.Add("collection") wordCollection.Add("of") wordCollection.Add("words") ' ----- Insert a word after item 3. wordCollection.Add("slightly", , , 3) ' ----- Insert a word before item 5. wordCollection.Add("longer", , 5) ' ----- Display the collection. For Each word As String In wordCollection    result.Append(word)    result.Append(Space(1)) Next word MsgBox(result.ToString( )) 

The results of these two "before and after" additions into the collection are shown in Figure 8-18.

Figure 8-18. Using a collection's Add( ) method to insert items at a given point


See Also

Recipes 8.17, 8.19, and 8.20 show other features of collections.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net