我找到并修改了以下代码,该代码运行良好但需要进行更多修改,我无法弄清楚。我希望它在相同的数值中随机排序。基本上我想要它做的是随机排序所有内容,然后按照降序排序(或列出)所有内容。例如,你会有一个名字和一个值,但它可能看起来像这样。名称2,名称2,名称2,名称3,名称4,名称4,名称4,名称5,名称8,名称8,等等。在它结束之前,我可以有大约500个名称,大约有8 0r 9个不同的值因此每个值组中有大约90个名称
Public Class Form1
Dim ListOfValues As New List(Of List(Of String))
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.txtA1.Focus()
End Sub
Private Sub AddTB(row As Integer, column As Integer, start As Char)
Dim tb As New TextBox
Dim offset As Integer = Math.Sign(Asc(start) - 65) * (100 + tb.Width * 3)
tb.Name = "txt" & Chr(row + Asc(start)) & column.ToString
tb.Text = tb.Name
tb.Location = New Point(((column - 1) * tb.Width) + offset, (row * tb.Height))
Me.Controls.Add(tb)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = True
For I = 0 To 9
ListOfValues.Add({Me.Controls("txt" & Chr(I + 65) & "1").Text, _
Me.Controls("txt" & Chr(I + 65) & "2").Text}.ToList)
Next
ListOfValues = ShuffleInfo(ListOfValues)
'This fills the other textboxes with the data from the shuffled list
For I = 0 To 9
Me.Controls("txt" & Chr(I + 77) & "1").Text = ListOfValues(I)(0)
Me.Controls("txt" & Chr(I + 77) & "2").Text = ListOfValues(I)(1)
Next
End Sub
Private Function ShuffleInfo(ValuesToShuffle As List(Of List(Of String))) As List(Of List(Of String))
'this follows the same basic routine you were using, swapping each item with a random item.
Dim rand As New Random(Now.Millisecond)
For counter = 0 To ValuesToShuffle.Count - 1
Dim n = rand.Next(counter + 1)
Dim temp As List(Of String) = ValuesToShuffle(counter)
ValuesToShuffle(counter) = ValuesToShuffle(n)
ValuesToShuffle(n) = temp
Next
ShuffleInfo = ValuesToShuffle
Button1.Enabled = False
End Function
End Class
答案 0 :(得分:1)
LINQ在这里很方便。看看这是否有帮助:
替换此行:
ListOfValues = ShuffleInfo(ListOfValues)
这一行:
ListOfValues = (From data In ShuffleInfo(ListOfValues)
Order By data(1) Descending).ToList
这将按列表中每个项目的第二个元素对列表进行分组,但在每个分组中保持顺序随机。
从这样的事情:
C 3
B 1
C 1
B 2
C 2
A 3
A 2
B 3
A 1
你明白了:
C 3
A 3
B 3
B 2
C 2
A 2
B 1
C 1
A 1