Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 524
  • Last Modified:

vb.net delete random from ArrayList

Hello,
I have an ArrayList called "lastnames" with 20 items.
I would like to know whats the easiest way to remove random items from it leaving it with only 5 records.. how can I do this?
0
XK8ER
Asked:
XK8ER
2 Solutions
 
BakuRetsu_XCommented:
Create a random number generator object up to the size of your matrix.
Once you grab a number, take that as your array index to remove from the array.
Are you looking for code example?

Search vb.net random number generator on google.
Then search remove from array list vb.net.
0
 
XK8ERAuthor Commented:
yeah I tried that but for example I do

myAL.RemoveAt(5)
myAL.RemoveAt(8)
myAL.RemoveAt(12)

at this point i have only 17 items in the arraylist so when I do

myAL.RemoveAt(19)

it crashes
0
 
käµfm³d 👽Commented:
Make sure the next random number you generate is never larger than the maximum index of your collection.

e.g.

Dim rand As New Random()
Dim myAL As New ArrayList() = SomeInitialization()
Dim toRemove As Integer = rand.Next(0, myAL.Count)

myAL.RemoveAt(toRemove)

Open in new window

0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Another quick example:
        Dim R As New Random
        While lastnames.Count > 5
            lastnames.RemoveAt(R.Next(lastnames.Count))
        End While

Open in new window

0
 
BakuRetsu_XCommented:
Remember.  The array is constantly shrinking also. So each time you want the random number to be within the length of it.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now