Is there an easy way to randomize a list in VB.NET?

后端 未结 8 1408
无人及你
无人及你 2020-12-02 00:35

I have a list of type System.IO.FileInfo, and I would like to randomize the list. I thought I remember seeing something like list.randomize() a li

8条回答
  •  攒了一身酷
    2020-12-02 01:00

    Build a Comparer:

    Public Class Randomizer(Of T)
        Implements IComparer(Of T)
    
        ''// Ensures different instances are sorted in different orders
        Private Shared Salter As New Random() ''// only as random as your seed
        Private Salt As Integer
        Public Sub New()
            Salt = Salter.Next(Integer.MinValue, Integer.MaxValue)
        End Sub
    
        Private Shared sha As New SHA1CryptoServiceProvider()
        Private Function HashNSalt(ByVal x As Integer) As Integer
          Dim b() As Byte = sha.ComputeHash(BitConverter.GetBytes(x))
          Dim r As Integer = 0
          For i As Integer = 0 To b.Length - 1 Step 4
              r = r Xor BitConverter.ToInt32(b, i)
          Next
    
          Return r Xor Salt
        End Function
    
        Public Function Compare(x As T, y As T) As Integer _
            Implements IComparer(Of T).Compare
    
            Return HashNSalt(x.GetHashCode()).CompareTo(HashNSalt(y.GetHashCode()))
        End Function
    End Class
    

    Use it like this, assuming you mean a generic List(Of FileInfo):

    list.Sort(New Randomizer(Of IO.FileInfo)())
    

    You can also use a closure to make the random value 'sticky' and then just use linq's .OrderBy() on that (C# this time, because the VB lambda syntax is ugly):

    list = list.OrderBy(a => Guid.NewGuid()).ToList();
    

    Explained here, along with why it might not even be as fast as real shuffle:
    http://www.codinghorror.com/blog/archives/001008.html?r=31644

提交回复
热议问题