Insert an Item into a Collection
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: Insert an Item into a Collection

  1. #1
    Join Date
    Dec 2012
    Posts
    38

    Insert an Item into a Collection

    Hi folks

    I've this trouble: I've several names grouped into an array of strings. The dimension of this array isn't fixed, because the user can add and remove an item from it. The array must be sorted, too. All these requests are difficult to carry out using an array, so, I decided to use a collection insted.

    To add and remove an item there are the direct methods, but to insert a new item between two already existing? What I've to do?

    I tried to use the Add method specifying the <Before> param but it raises an error. The code used is below:
    Code:
    Dim c As New Collection
    
    Private Sub Command2_Click()
        Dim i As Variant
        
        For Each i In c
            MsgBox i
        Next i
    End Sub
    
    Private Sub Form_Load()
        With c
            .Add "Giovanni"
            .Add "Marco"
            .Add "Valeria"
        End With
    End Sub
    
    
    Private Sub Command1_Click()
        Dim i As Variant
        Dim s As String
        
        s = InputBox("Inserisci 1 nome")
        For Each i In c
            If Asc(i) > Asc(s) Then
                c.Add s, , i                              'Here the error raises.
            End If
        Next i
    End Sub
    If I was not clear enough, please tell me. Thanks to anyone who tries to help me.

  2. #2
    Join Date
    Jul 2005
    Posts
    1,074

    Re: Insert an Item into a Collection

    Maybe a Dictionary is the solution.... read next article
    ----------------------------------------------------
    Using the Dictionary Object
    by Alex Dinu
    December 6, 1999

    What is it and why use it?

    Visual Basic and VB Script were never any good working with large arrays and

    lookup tables. So the Microsoft ASP team decided to create a component that

    will be the equivalent to the Perl hash, or associative array. It first came

    out in 1996 as part of VB Script 2 and was added to the VB Scripting run-time

    library (scrrun.dll) to enable VBScript programmers to use associative

    arrays. Now you can develop in Visual Basic or VB Script just as you would in

    JScript and Perl. For more information read this very nice and interesting

    article

    OK, but what is it actually used for?

    I was given a problem, not too long ago, that required me to compare two very

    large sets of data. They were both over 300,000 lines.

    No problem, I said, give me a couple of minutes, and I will then give you the

    differences between the two lists. The data I needed to compare was a simple

    one, a key and a value. I was required to first report of any keys found in

    one list and not in the other, and if the key was there, I then had to make

    sure that the values were also the same.

    I quickly created a multidimensional array for each list, populated the

    arrays, which took a while, but then adding 300,000 values into a

    multidimensional is not a quick process, and started the comparison. Needless

    to say, it didn’t return me any results – my machine died on me before any

    results were displayed.

    I went back and said that it will take me a little longer, and that I needed

    more memory, when I remembered about the dictionary object. This method was

    not only quicker, but also easier (for me that is) to use, and I’m not

    talking about the MS Word dictionary here.

    A dictionary holds two sets of information, a unique key and a value

    associated with the key, so we use the key to retrieve the item. The key can

    be anything except a variant, but it’s should usually be an integer or a

    string. The item can be of any type.

    Before I bore you with all the details, let us start up Visual Basic, and

    create a new EXE project.

    ------
    Add the dictionary object references by opening the project references from

    the Project menu and adding the Microsoft Scripting Runtime.
    -------
    The next step would be to define and declare the dictionary object.

    Code:
    Dim Dict1 As Dictionary
    The next step is to create the dictionary and populate it with keys and

    items.

    Code:
    ' Create a dictionary instance.
    Set Dict1 = New Dictionary
    
    With Dict1
      'set compare mode
      .CompareMode = BinaryCompare
      ' Add items to the dictionary.
      .Add 1, "Item 1"
      .Add 2, "Item 2"
      .Add 3, "Item 3"
    End With
    We now have a dictionary object that holds 3 rows with key values 1 to 3 and

    their associated item values. The Compare Mode sets and returns the

    comparison mode for comparing string keys in a Dictionary object. The values

    can be vbBinaryCompare, vbTextCompare or vbDatabaseCompare. Remember to set

    the Compare Mode before you add any data to the dictionary otherwise you will

    get an error.

    So now we have a dictionary object, containing some data ready to be

    accessed. Lets take a look at a couple of methods we have available, to look

    up keys and items within a dictionary object.

    The Exists method is used to find a specific key in the dictionary object.

    Say for example that you want to find out if you have the object contains a

    key with a value of 1999. We use the following syntax to get either a true or

    false:
    Code:
    Dim bReturnValue As Boolean
    bReturnValue = Dict1.Exists(1999)
    In this case, it will return False.

    If you wish to get the item of a specific key, use the Items method, which

    has the following syntax:
    Code:
    Dim vItemValue As Variant
    vItemValue = Dict1.Item(3)
    Which in this case will return you "Item 3".

    Lets take a look now at how we could compare two dictionaries, find any items

    that are in one and not the other, and if any key items are different.

    First, lets populate two dictionary objects with keys and items. Notice that

    by using the following code, we have 3 differences: key 1 is different, key 4

    is not in Dict1 and key 3 is not in Dict2.
    Code:
    ' Declare the dictionaries.
    Dim Dict1 As Dictionary
    Dim Dict2 As Dictionary
    
    ' Create a variant to hold the object.
    Dim vContainer1
    Dim vContainer2
    
    ' Create the dictionary instances.
    Set Dict1 = New Dictionary
    Set Dict2 = New Dictionary
    
    With Dict1
      'set compare mode
      .CompareMode = BinaryCompare
      ' Add items to the dictionary.
      .Add 1, "Item 1"
      .Add 2, "Item 2"
      .Add 3, "Item 3"
    End With
    
    With Dict2
      'set compare mode
      .CompareMode = BinaryCompare
      ' Add items to the dictionary.
      .Add 1, "Item 1a"
      .Add 2, "Item 2"
      .Add 4, "Item 4"
    End With
    
    ' Compare the two dictionaries.
    For Each vContainer1 In Dict1
      If Not Dict2.Exists(vContainer1) Then
        Debug.Print vContainer1 & " is in Dict1 but not in Dict2"
      Else ' Item exists so lets check the size.
        If Dict2.Item(vContainer1) <> Dict1.Item(vContainer1) Then
          Debug.Print "Key item " & vContainer1 & " is different"
        End If
      End If
    Next
    The results of the above code is:

    Key item 1 is different

    3 is in Dict1 but not in Dict2

    Remember that we now have to step through each Dict2 line to find the last

    difference we forced, but I’m sure you can do that.

    Conclusion

    Many of you would be asking, why not use an array. Well, try and do this with

    a multidimensional array with 300,000 lines of data, and you would see

    straight away why. It takes roughly 2-3 minutes to add 300,000 lines of data

    into a dictionary, and 4-5 minutes to compare the two dictionaries, depending

    on your PC type and memory.
    JG


    ... If your problem is fixed don't forget to mark your threads as resolved using the Thread Tools menu ...

  3. #3
    Join Date
    Jan 2006
    Location
    Chicago, IL
    Posts
    14,985

    Re: Insert an Item into a Collection

    I'd give it an A- for HOMEWORK...
    David

    CodeGuru Article: Bound Controls are Evil-VB6
    2013 Samples: MS CODE Samples

    CodeGuru Reviewer
    2006 Dell CSP
    2006, 2007 & 2008 MVP Visual Basic
    If your question has been answered satisfactorily, and it has been helpful, then, please, Rate this Post!

  4. #4
    Join Date
    Dec 2012
    Posts
    38

    Re: Insert an Item into a Collection

    Dear jggtz,
    don't I have understood your answer or your reply hasn't nothing to do with the question?

    What I need it's an easy way to insert a new item among others, so that the structure that contains data is always sorted. I thought that Collection could do that (using the specific param <Before> of the Add method). But giving a look to the MSDN I realized why the code I posted before doesn't work.

    Also using a Dictionary (thing that I tried first of all) doesn't solve the problem, nay, it complicates the situation for two basic reasons: first I should use an external structure while VB already gives something like that. Then, a Dictionary doesn't give the possibility to insert an item before or after another one. There are other reason for which I prefere to avoid to use it.

    However, anyone who wants to help me come forward

  5. #5
    Join Date
    Jul 2005
    Posts
    1,074

    Re: Insert an Item into a Collection

    Sorry... I copy/paste an old file that I did think was a Dictionary tutorial...

    Anyway...

    You could use an invisible listview control
    it's a sorted array
    it has methods to find items
    etc.
    JG


    ... If your problem is fixed don't forget to mark your threads as resolved using the Thread Tools menu ...

  6. #6
    Join Date
    Dec 2012
    Posts
    38

    Re: Insert an Item into a Collection

    I can't use objects such as listbox or other because data are put or get from different points of the program, and not always the form cointaing the object is visible or loaded in memory.

    The only way is to use a public declaration in a module, and write an algorithm to sort

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center