Collections.shuffle() equivalent in vb.net?

2020-04-16 18:14发布

问题:

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.

回答1:

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.

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


标签: java .net vb.net