Delete Data From Arrays

  • 13 years ago

    I have the following Arrays:

     Names () As String

    Salaries() As Decimal

    Names(0) = "Bob"             Salaries(0) = "100"

    Names(1) = "Fred"            Salaries(1) = "200"

    Names(2) = "Jack"           Salaries(2) = "300"

    Now I have a variable called intLocation that keeps track of where I am in the array, and I present the user with an input box that says "Enter the name of the person you want to delete"

    Now I figure I can write a For Loop to cycle through the array and find the person I am looking for (save array index to intLocation?). Now I've got to delete that person and their salary from the arrays......

    It would do me no good to just simply write for example Names(1) = String.Empty and Salaries(1) = String.Empty

    because then if I write the data on the screen, I would see a gap in my list.....

    So the question is, if I wanted to delete Fred from the array and his salary of 100, how would I move up Jack and his salary where Fred used to be along with any other data that may be below Jack that would also have to be moved up by 1?

  • 13 years ago

    If you have at least installed the .Net framework 2.0 you may want to have a look at System.Collections.Generics.List(of T) and its example.

    A list behaves very much like an array but when you remove an item a list closes the "gap" automatically.

  • 13 years ago

    Collections also work in this way.

    The best method will involve creating a class to represent the person.

    This will have a name (let us assume this is unique)   as a string  attribute,

    and a salary   as a double    attribute.

     

    Then you create new people on demand, using something like

     thePerson = new (myPerson) 

    thePerson.name = "Jim"

    thePerson.salary = 23000

     

    Then you can add it to the collection:

    MyCollection.Add   thePerson,thePerson.Name        would probably do

     

    To see the contents of the collection, use

    for each APerson in MyCollection

       msgbox APerson.name 

     

    And to remove one,

     

    MyCollection.Remove ("Jim")

     

     

     

     

     

     

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.” - Antoine de Saint Exupéry