在vb.net中的Collections.shuffle()等效?

Dob*_*obr 2 .net java vb.net

什么是java.util.Collections.shuffle()vb.net方法的等价物?我没有在MSDN上找到类似的东西.非常感谢帮助.

drf*_*drf 6

有(据我所知)没有内置的.NET函数,但使用Linq很容易编写一般的等价函数:

Function Shuffle(Of T)(collection As IEnumerable(Of T)) As List(Of T)
    Dim r As Random = New Random()
    Shuffle = collection.OrderBy(Function(a) r.Next()).ToList()
End Function
Run Code Online (Sandbox Code Playgroud)

调用此函数会为输入列表中的每个元素分配一个随机值,然后按该随机数排序,返回一个新的(混洗)列表.

如果集合是一个数组或派生自IList,那么更高效的方法可能是使用Fisher-Yates算法来就地重新排列列表:

Sub Shuffle(Of T)(list As IList(Of T))
    Dim r As Random = New Random()
    For i = 0 To list.Count - 1
        Dim index As Integer = r.Next(i, list.Count)
        If i <> index Then
            ' swap list(i) and list(index)
            Dim temp As T = list(i)
            list(i) = list(index)
            list(index) = temp
        End If
    Next
End Sub
Run Code Online (Sandbox Code Playgroud)