vb.net中的Collections.shuffle()是否等效

问题描述:

vb.net的 java.util.Collections.shuffle()方法等效于什么?我没有在MSDN上找到任何类似的东西。非常感谢您的帮助。

Whats the equivalent for java.util.Collections.shuffle() method for vb.net? I did not find anything similar on MSDN. Help is very much appreciated.

(据我所知)没有内置的.NET函数,但是使用Linq可以很容易地写出一个普通的等价物:

There is (as far as I can tell) no built-in .NET function, but a general equivalent is easily written using 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

调用此函数可为输入列表中的每个元素分配一个随机值,然后按该随机数排序,返回

Calling this function assigns a random value to each element in an input list, and then sorts by that random number, returning a new (shuffled) list.

如果集合是数组或源自 IList ,则性能更高可能是使用 Fisher-Yates算法来在列表中随机排列位置:

If the collection is an array or derives from IList, a more performant approach could be to use the Fisher-Yates algorithm to shuffle the list in-place:

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