Collections.shuffle() equivalent in vb.net?

后端 未结 1 462
梦毁少年i
梦毁少年i 2021-01-22 17:50

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条回答
  • 2021-01-22 18:30

    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
    
    0 讨论(0)
提交回复
热议问题