I am trying to take Items that I have already added to a list.
Dim lista As New List(Of String)
n = 2
i = 0
Do While i < n + 1
Randomize()
a = Int(Rnd() * 4) + 1
If a = 1 Then
lista.Add("1b")
ElseIf a = 2 Then
lista.Add("2b")
ElseIf a = 3 Then
lista.Add("3b")
ElseIf a = 4 Then
lista.Add("4b")
End If
i = i + 1
Loop
Lets imagine that the list i got was {2b,4b,1b}. Now i want to know how to get lets say just 2b from the list as a first Item and then delete it from the list.
This would be a good place to use a Queue(Of )
.
Dim item As String
item = queuea.Dequeue
But List(Of )
has an indexer so you can just use it like an array:
Dim item As String
item = lista(0)
' Then remove the first item:
lista.RemoveAt(0)
Use the .net Random
class instead of the old VB6 methods. Calling Random.Next(Interger1, Integer2)
will return an Integer
equal to or greater than Integer1
and less than Integer2
. Note that since the values are so limited there is a good chance of having duplicates in the list.
Although multiple ElseIf
s will work, a Select Case
is easier to read and less typing.
I put the contents of the list in a ListBox
so we could see what was going on. I used the Remove
method of List(Of T)
then rebind the ListBox
.
Private lista As New BindingList(Of String)
Private rand As New Random
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BuildList()
ListBox1.DataSource = lista
End Sub
Private Sub BuildList()
Dim i = 0
Dim a As Integer
Do While i < 3 'since n never changes just use the literal value
a = rand.Next(1, 5)
Select Case a
Case 1
lista.Add("1b")
Case 2
lista.Add("2b")
Case 3
lista.Add("3b")
Case 4
lista.Add("4b")
End Select
i = i + 1
Loop
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 'Remove from list
lista.Remove(ListBox1.SelectedItem.ToString)
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.